【问题标题】:Why there is a gap between Keyboard and the View when keyboard appears为什么键盘出现时键盘和视图之间有间隙
【发布时间】:2018-02-05 15:46:16
【问题描述】:

结构:

UIView

基础视图

自动布局

  1. 中心 X
  2. Y 中心
  3. 与 SafeView 等宽
  4. 与 SafeView 等高

UIView

InnerView(BaseView 的子视图)

自动布局

  1. 领先
  2. 尾随
  3. 顶部
  4. 底部(创建名为“bottomLayoutConstraint”的 IBOutLet)

    - (void)keyBoardWillShow:(NSNotification *)notification {

        NSDictionary *info  = notification.userInfo;
        NSValue      *value = info[UIKeyboardFrameEndUserInfoKey];
        CGRect rawFrame      = [value CGRectValue];
        CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
        self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame);
[self.view layoutIfNeeded];

    }

    - (void)keyBoardWillHide:(NSNotification *)notification {

        self.bottomLayoutConstraint.constant = 0.0;

    }

为什么出现键盘时KeyboardInnerView 之间有间隙?


编辑:

应用 Aleksander Maj 的解决方案后,差距缩小到 5px


编辑:

这是我的视图层次截图

【问题讨论】:

    标签: ios objective-c uiview autolayout


    【解决方案1】:

    CGRectGetHeight(keyboardFrame) 返回从屏幕底部边缘算起的键盘高度。同时,您的bottomLayoutConstraint 被固定到您的BaseView 安全区域的底部边缘(与屏幕底部边缘不同)。这两个水平指南之间的差异是您的差距的高度。 您应该按以下方式计算bottomLayoutConstraint 的常数:

    if (@available(iOS 11, *)) {
      self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame) - self.view.safeAreaInsets.bottom
    } else {
      self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame)
    }
    

    至少我是这么怀疑的。我没有重现您的视图层次结构。


    编辑:

    您能否粘贴您的视图层次结构的屏幕截图(已展开所有约束)?我认为您对 5pt 差距的问题可能与不正确的约束常数值有关。


    编辑 2:

    【讨论】:

    • 感谢您的回复,请查看我在问题中添加的编辑和新屏幕截图,这些屏幕显示在应用您的解决方案后将差距缩小到 5px。为什么还有 5px 的差距?
    • 您的视图层次结构中可能存在第二个问题。请参阅我编辑的答案。
    • 请在我的问题中查看查看层次结构截图。
    • BaseView.centerY = centerY 是导致问题的原因。您应该将您的 BaseViewcenterY 限制为 Safe Area 的 centerY。应该说BaseView.centerY = Safe Area.centerY
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多