【问题标题】:iOS: scrollView not scrolling to correct position when keyboard visibleiOS:当键盘可见时,scrollView 没有滚动到正确的位置
【发布时间】:2014-10-31 12:10:24
【问题描述】:

我正在使用 6.1 模拟器测试我的 iOS 应用程序。当键盘可见时(在用户单击 textView 之后),我已经工作了几个小时将我的 scrollView 滚动到正确的位置。我已尝试按照此页面上标记为正确的答案进行操作:

How do I scroll the UIScrollView when the keyboard appears?

这是我目前拥有的:

- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSLog(@"keyboardWasShown");

    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.activeView.frame.origin) ) {
        NSLog(@"scrollToView");
        CGPoint scrollPoint = CGPointMake(0.0, self.stepDescriptionField.frame.origin.y-kbSize.height);
        NSLog(@"scrollPoint: %f", scrollPoint.y);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }

}

从上图可以看出,如果用户点击textView,scrollView并没有滚动到正确的位置(应该可以看到textView的文本内容)。

奇怪的是,我手动尝试将 scrollPoint 的 y 偏移更改为不同的值,但它似乎对窗口滚动到的位置没有影响。 我做错了什么?

其他可能很重要的事情:

  • 我已关闭自动布局(以便用户可以在此视图中垂​​直滚动)。
  • textView 不可滚动(已调整大小以适合其内容)

编辑

我发现如果我将我的偏移量添加到 contentInsets 如下:

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0);

视图将滚动到正确的位置。唯一的缺点是底部有额外的填充:

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: ios objective-c uiscrollview keyboard


    【解决方案1】:

    我将它与 UITextField 而不是 UITextView 一起使用,但我相信它应该仍然可以正常工作。这使我可以将文本字段直接定位在键盘上方。

    keyboardWillShow是NSNotificationCenter收到UIKeyboardWillShowNotification时的函数

    -(void) keyboardWillShow:(NSNotification *)note
    {
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];
    
    // Start animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
    
    
    // Get Keyboard height and subtract the screen height by the origin of the textbox and height of text box to position textbox right above keyboard
    self.scrollView.contentOffset = CGPointMake(0,keyboardBounds.size.height-([UIScreen mainScreen].bounds.size.height - commentBox.frame.origin.y - commentBox.frame.size.height));
    
    [UIView commitAnimations];
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 2017-03-25
      • 2012-07-01
      • 2019-04-29
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多