【问题标题】:Move screen up when keyboard appears in iPhone X当键盘出现在 iPhone X 中时向上移动屏幕
【发布时间】:2018-09-10 21:52:01
【问题描述】:

我使用下面的代码在键盘显示和隐藏时上下移动屏幕

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}

@objc func keyboardWillShow(notification: NSNotification) {        
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

@objc func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

它适用于除 iPhone x 以外的所有设备(我认为问题是 iPhone X 底部浪费了空间)

问题是键盘大小在显示之前和之后发生变化,导致视图上下移动......

谁能帮忙?

【问题讨论】:

  • 好吧,我遇到的问题与我最终使用 iqKeyboardmanager 并设置输入字段和键盘 40 之间的距离相同。
  • 再次让你惊叹@PratikPrajapati :) 我可以看看你的代码吗?

标签: ios swift uikeyboard


【解决方案1】:

您还应该考虑安全区域插入

let endFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero
let bottomSpace = keyboardValues.endFrame.maxY - keyboardValues.endFrame.minY - self.view.safeAreaInsets.bottom

而且你不应该是累加的。这些通知可能会发布多次。使用绝对值。

【讨论】:

    【解决方案2】:

    来了, 使用IQKeyboardManagerSwift

    AppDelegate.swift 设置

    IQKeyboardManager.shared.enable = true
    IQKeyboardManager.shared.enableAutoToolbar = false
    

    在我的视图控制器中

    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        print(#function)
        if DeviceType.checkiPhoneX() {
            IQKeyboardManager.shared.keyboardDistanceFromTextField = 40.0
        }        
        return true
    }
    
     func textViewDidEndEditing(_ textView: UITextView) {
        if DeviceType.checkiPhoneX() {
            IQKeyboardManager.shared.keyboardDistanceFromTextField = 0.0
        }
    }
    

    这就是我为 X 管理键盘的方式。

    希望对您有所帮助。

    【讨论】:

    • 无需外部库即可轻松处理键盘。
    • 是的,我只是按照他的要求展示我尝试过的代码
    【解决方案3】:

    使用 UIKeyboardFrameEndUserInfoKey 代替 UIKeyboardFrameBeginUserInfoKey。

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2012-08-13
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多