【问题标题】:UIKeyboard height different after device rotation设备旋转后 UIKeyboard 高度不同
【发布时间】:2018-03-30 07:40:26
【问题描述】:

我有设备旋转后键盘高度的问题:

guard let keyboardSize = sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }

let keyboardHeight = keyboardSize.cgRectValue.height

与正常值不同。正常键盘高度(在测试设备上)为 398,旋转后高度为 142。

更多上下文:

我编写了一个仅限 iPad 的应用程序,该应用程序的视图始终应保持在中心 (Y),即使显示键盘也是如此。对于这种情况,我将中心 Y 约束作为出口。我为 UIKeyboardWillShowUIKeyboardWillHide 通知注册了我的 ViewController。当调用隐藏通知时,我将约束常量设置为 0。当调用显示通知时,我根据剩余的视图空间 (view.height - keyboard.height) 计算新的中心 Y。

当第一次调用UIKeyboardWillShow 时,一切正常。但是在我旋转设备后,键盘高度不同,我的计算给了我一个错误的值。

如何在显示键盘的情况下正确计算旋转后的中心 Y?

【问题讨论】:

    标签: ios swift ipad rotation uikeyboard


    【解决方案1】:

    Farhan Arshad 说得对,UIKeyboardFrameEndUserInfoKey 会给你更好的结果,但它并没有解决你提到的问题。

    当您注册 UIKeyboardWillShow(或 UIKeyboardWillChangeFrame)时,当您从纵向旋转到横向时,您实际上会收到多个通知。第一个通知的键盘高度为 142 像素,第二个通知的键盘高度为 398 像素。为您的约束值使用第二个通知,它应该可以解决您的问题。

    【讨论】:

      【解决方案2】:

      好的做法是添加/删除观察者:

      override func viewDidAppear(_ animated: Bool) {
              NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
          }
      
      
      override func viewDidDisappear(_ animated: Bool) {
          NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
      }
      

      这是解决您问题的关键 试试看UIKeyboardFrameEndUserInfoKey

      Swift4 需要@objc

          @objc func keyboardWillShow(notification: NSNotification) {
            if let keyboardSize = (notification.userInfo? 
            [UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
      
                      //Your code here
      
            }
          }
      

      【讨论】:

      • 虽然 UIKeyboardFrameEndUserInfoKey 在正常情况下是用来获取keyboardSize的合适的部分,但它并不能解决问题。
      猜你喜欢
      • 2011-07-10
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多