键盘出现后,UISCcrollView的contentSize会发生变化

时间:2013-02-08 10:56:43

标签: iphone ios objective-c cocoa-touch uiscrollview

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

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

不幸的是,存在不良行为:我的scrollView的contentSize属性会因键盘的高度而增加。因此,当键盘仍然可见时,我可以滚动视图,但在适当的内容下方会出现一个空白区域。这是我想避免的事情。我知道这是由更改contentInset属性引起的,所以也许还有另一种方法来做这件事而没有副作用。

首先,我注册了UIKeyboardDidShowNotificationUIKeyboardWillHideNotification的观察员:

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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];
相关问题