【问题标题】:Move menu when the keyboard opens (Swift)键盘打开时移动菜单(Swift)
【发布时间】:2020-06-05 19:35:14
【问题描述】:

我的函数“keyboardWillShown”有问题。所以我想要的是我的菜单在打开时正好出现在键盘上方。它在 Iphone 8 plus、8、7、6 上完美运行。但是当我在模拟器上运行 Iphone 11 时,结果如下。

Picture of how it looks in Iphone 11

Constrains

这是我的代码:

@objc func keyboardWillShown(notification: NSNotification) {
    let info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    UIView.animate(withDuration: 0.1, animations: { () -> Void in
        self.keyboardConstrains.constant = keyboardFrame.size.height
    })
}

调用函数

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShown(notification:)), name:  UIResponder.keyboardWillShowNotification, object: nil )
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver( self,name:  UIResponder.keyboardWillShowNotification, object: nil )
}

【问题讨论】:

    标签: ios swift iphone xcode keyboard


    【解决方案1】:

    您可以根据屏幕大小设置约束

    if self.view.height >= 800{ //For bigger screens (X ,11)
        self.keyboardConstrains.constant = keyboardFrame.size.height - 50
    } else {
        self.keyboardConstrains.constant = keyboardFrame.size.height
    }
    

    【讨论】:

    • 这听起来像是一个很好的解决方案,但是当我这样做时,我得到错误“'UIView' 类型的值没有成员'高度”。你知道它可能是什么吗?
    • 尝试使用-> self.view.frame.size.height
    【解决方案2】:
    let window = UIApplication.shared.keyWindow
    let bottomPadding = window?.safeAreaInsets.bottom
    keyboardConstrains.constant = (keyboardSize?.height)! - (bottomPadding ?? 0)
    

    这是因为所有缺口 iPhone(X、Xr、iPhone11 等)在底部也有安全区域,所以键盘高度从主视图计算,并且您从安全区域设置“keyboardConstrains”,这就是这个空间出现的原因。要删除此空间,您必须检查底部是否有安全区域,而不是从键盘高度减去底部空间。

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2015-07-09
      • 2020-01-16
      相关资源
      最近更新 更多