我已经实现了一项功能,当键盘隐藏选定的文本输入时自动滚动视图(我的和教程中的实际上是相同的)。
不幸的是,有一个不良行为:我的滚动视图的contentSize
属性随着键盘的高度而增加。因此,当键盘仍然可见时,我可以滚动视图,但在正确的内容下方会出现一个空白区域。这是我想避免的事情。我知道这是由更改contentInset
属性引起的,所以也许有另一种方法可以做到这一点而不会产生副作用。
UIKeyboardDidShowNotification
首先,我为and注册观察者UIKeyboardWillHideNotification
:
- (void)registerKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
这个函数在viewWillAppear
. 方法keyboardWasShown
和keyboardWillBeHidden
外观如下:
- (void)keyboardWasShown:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
CGRect rect = self.view.frame;
rect.size.height -= kbSize.height;
if(!CGRectContainsPoint(rect, activeField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, 2*activeField.frame.size.height+activeField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification *)notification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
正如我之前写的,它基本上是苹果的解决方案。