在 UITextField 在 iOS 中激活后显示键盘时,试图限制 UIScrollView 内的滚动区域

Trying to limit scroll area inside a UIScrollView when displaying the keyboard after a UITextField becomes active in iOS

我正在做一个项目,其中有一个 UIView,其中包含多个 UI 元素,包括一个 UITextField。一旦 UITextField 变为活动状态(即 becomesFirstResponder),弹出的键盘将覆盖 UITextField。包含所有 UI 元素的 UIView 位于 UIScrollView.

现在,除了将 contentView 向上移动到 UIScrollView 的可见区域之外,我需要做的另一件事是确保用户无法将 contentView 滚动到键盘下方(和后面),也不会在上面(和导航栏后面)滚动 contentView。

我目前的相关代码是:

-(void)keyboardDidShow:(NSNotification *)notification {
    CGFloat height = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    self.scrollViewBottomContstraint.constant = height;
    [self.view layoutIfNeeded];

}

任何人都可以告诉我如何确保我的 contentView 只能在导航栏和键盘之间的可见区域内滚动最少吗?

这可能对您有所帮助。

//KEYBOARD SHOWN
    - (void)keyboardShown:(NSNotification*)notification
    {
        NSDictionary* dic = [notification userInfo];
        CGSize keyboardSize = [[dic objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;

        CGPoint scrollPoint = CGPointMake(0.0, textField.frame.origin.y-keyboardSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];

    }

      //when keyboard hides
    - (void)keyboardHidden:(NSNotification*)notification
    {
        // Set the Scroll view content inset to UIEdgeInsetsZero
    }

当出现键盘通知时,我会:

  1. 更改 UIScrollView 上的约束常量,使其大小正好适合屏幕的可见部分。您已经使用底部约束的高度设置开始了这条路径。
  2. 更改 UIScrollView 上的 contentSize 属性 以匹配。这样,用户执行的任何滚动都仅限于他们可见的内容。

键盘消失后,您可以恢复到进行这些调整之前的先前设置。

请注意,在某些情况下,使用带有静态 table 单元格和静态内容的 UITableView 会更容易。 iOS 运行时似乎可以处理一些滚动,让您看到它们。