Move screen up when keyboard appears in iPhone X

时间秒杀一切 提交于 2019-12-11 12:30:00

问题


I use code below to move screen up and down when keyboard show and hide

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

It works in all devices except iPhone x (I think the problem is iPhone X bottom wasted space)

Problem is that keyboard size change before shown and after that and cause the view go down and down and down...

Can anyone help?


回答1:


Here it is, Use IQKeyboardManagerSwift

AppDelegate.swift settings

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

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

This is how i manage Keyboard for X.

Hope this may help you.




回答2:


You should also consider safe area insets

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

And you should not be additive. These notifications may be posted multiple times. Use absolute values.




回答3:


Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey.



来源:https://stackoverflow.com/questions/52232926/move-screen-up-when-keyboard-appears-in-iphone-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!