3

基于: https ://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

我已经实现了一项功能,当键盘隐藏选定的文本输入时自动滚动视图(我的和教程中的实际上是相同的)。

不幸的是,有一个不良行为:我的滚动视图的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. 方法keyboardWasShownkeyboardWillBeHidden外观如下:

- (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;
 }

正如我之前写的,它基本上是苹果的解决方案。

4

2 回答 2

1

内容插入旨在允许访问可能隐藏在键盘下方的滚动视图部分(例如)。因此,如果您的内容底部有一个文本视图,用户将无法与之交互,因为它会隐藏在键盘窗口下方。使用内容插入(根据 Apple 示例),您可以滚动更多内容,并显示文本视图。它实际上并没有增加contentSize属性。

请在此处阅读更多信息:http: //developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/UIScrollView_pg/CreatingBasicScrollViews/CreatingBasicScrollViews.html

于 2013-02-08T20:57:26.597 回答
0
CGFloat contentSizeHeight = contentSize.height;
CGFloat collectionViewFrameHeight = self.collectionView.frame.size.height;
CGFloat collectionViewBottomInset = self.collectionView.contentInset.bottom;
CGFloat collectionViewTopInset = self.collectionView.contentInset.top;
CGPoint bottomOffsetForContentSize = CGPointMake(0, MAX(-collectionViewTopInset, contentSizeHeight - (collectionViewFrameHeight - collectionViewBottomInset)));
[self.collectionView setContentOffset:bottomOffsetForContentSize animated:animated];
于 2015-05-19T14:05:44.990 回答