当键盘出现在 iPhone X 时向上移动屏幕

Move screen up when keyboard appears in iPhone X

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

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
        }
    }
}

除iPhonex外,它在所有设备上都有效(我认为问题是iPhone X底部浪费了space)

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

有人可以帮忙吗?

使用 UIKeyboardFrameEndUserInfoKey 而不是 UIKeyboardFrameBeginUserInfoKey。

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

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

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

在这里, 使用 IQKeyboardManagerSwift

AppDelegate.swift 设置

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

在我的ViewController

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 键盘的方式。

希望对您有所帮助。