交互式关闭键盘时如何检测键盘框架的变化?

时间:2015-10-27 08:26:53

标签: ios objective-c

考虑到这种情况,我在故事板中以交互方式设置了键盘Dismiss的textview,因此当用户向下滚动并能够以交互方式关闭键盘时。 我对textview有限制,以确保它始终完全显示在视图上。

当前的问题是,当用户逐渐向下滚动以关闭键盘时,我无法检测到键盘框架的变化。我尝试了UIKeyboardWillHideNotificationUIKeyboardWillChangeFrameNotification,只有在键盘解除后才会调用它们。

所以我的问题是,当交互式关闭键盘时,我们如何同时检测键盘框架的变化?

3 个答案:

答案 0 :(得分:6)

如果您想要观察键盘框架更改,即使在拖动键盘时也可以使用此功能:https://github.com/brynbodayle/BABFrameObservingInputAccessoryView

基本上,您为键盘创建了一个占位符输入视图(即使在拖动时也始终粘在键盘上)并观察它的帧更改。这些更改将在一个块中返回,因此您始终可以获得键盘的当前帧。

答案 1 :(得分:5)

您不应该更改textView高度以适合所有视图。相反 - 您应该更改 contentInset 字段,以便textView保持相同的高度,并且您不必费心去跟踪交互式键盘的跟踪框架。 在这里看到答案: How do I scroll the UIScrollView when the keyboard appears?

答案 2 :(得分:-3)

在viewDidLoad方法中添加以下行:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWillShow:)
                                         name:UIKeyboardWillShowNotification
                                       object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillHide:)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];

将这些方法添加到viewController

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.30
                          delay:0.0
                        options:(7 << 16) // This curve ignores durations
                     animations:^{
                         self.buttonsBottomConstraint.constant = keyboardSize.height - self.footerView.bounds.size.height + 4.0;
                         [self.view layoutIfNeeded];
                     }
                     completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.30
                          delay:0.0
                        options:(7 << 16) // This curve ignores durations
                     animations:^{
                         self.buttonsBottomConstraint.constant = 0.0;
                         [self.view layoutIfNeeded];

                     }
                     completion:nil];


}
相关问题