【问题标题】:How to handle Keyboard with safe area in iphone x Using AutoLayout? [duplicate]如何使用自动布局在 iphone x 中处理具有安全区域的键盘? [复制]
【发布时间】:2017-12-18 11:45:55
【问题描述】:

在 iphone x 中设置安全区域后。当键盘打开安全区(键盘上方的白色区域)出现在键盘上方时,如何处理键盘?

键盘上方的白色区域。

处理键盘代码:-

func keyboardWillChangeFrameWithNotification(_ notification: Notification, showsKeyboard: Bool) {

        let userInfo = notification.userInfo!
        let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        // keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
        let keyBoardRect = self.view.convert(keyboardScreenEndFrame, from:nil)

        UIView.animate(withDuration: animationDuration, delay: 0, options: .beginFromCurrentState, animations: {

            // Keyboard is going to appear. move composebar up
            if showsKeyboard {
                self.constraintBottomAttachmentView.constant =  keyBoardRect.size.height
            } else { // Keyboard is going to disappear. Move composebar down.
                self.constraintBottomAttachmentView.constant = 0
            }

            self.view.layoutIfNeeded()
            }, completion: { finished in
                // Update the height of recipient bar.
                self.updateRecipientBarMaxHeight()
        })
    }

iphone x 中的键盘高度增加了,所以如果我从键盘高度减去 - 34,白色区域会减小。 代码:-

if showsKeyboard {
                  self.constraintBottomAttachmentView.constant =  keyBoardRect.size.height - self.view.safeAreaInsets.bottom /*(34)*/ } 

那么如何在不手动执行此操作的情况下以优化的方式解决此问题?

【问题讨论】:

    标签: ios iphone swift ios11 safearealayoutguide


    【解决方案1】:

    您可以通过以下方式获取 iPhone X 底部空间的高度:

    view.safeAreaInsets.bottom
    

    请记住,这仅适用于 iOS 11 及更高版本,因此您需要此条件:

    if #available(iOS 11.0, *) {
    //Move Composebar for iOS 11
    } else {
    //Move Composebar for other Versions
    }
    

    在您的情况下,这看起来类似于:

    if showsKeyboard {
          if #available(iOS 11.0, *) {
              self.constraintBottomAttachmentView.constant =  keyBoardRect.size.height - view.safeAreaInsets.bottom
          } else {
              self.constraintBottomAttachmentView.constant =  keyBoardRect.size.height
    } else { // Keyboard is going to disappear. Move composebar down.
          self.constraintBottomAttachmentView.constant = 0
    }
    

    这对你有用吗?

    【讨论】:

    • 我已经在上面写了这段代码,我想要优化的方式,而无需使用自动布局从代码中手动更新约束。
    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 2018-03-02
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多