I tried to implement a Notification that alerts the view that the Keyboard will appear and should shift upwards with the keyboards height.
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
}
Here is the KeyboardWillShow method body:
@objc func KeyboardWillShow(_ notification: Notification) {
view.frame.origin.y -= getKeyBoardHeight(notification)
}
and the getKeyBoardHeight function:
func getKeyBoardHeight(_ notification: Notification) -> CGFloat {
let userinfo = notification.userInfo
let keyboardsize = userinfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardsize.cgRectValue.height
}
Why does my app shift completely out of view and when I toggle the keyboard on in the simulator?
These are the methods I use on a regular basis that work, I think your issue is with using -= getKeyboardHeight
, try the code in my keyboardWillShow
method below
class VC: UIViewController {
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillHide(notification: NSNotification) {
view.frame.origin.y = 0
}
@objc func keyboardWillShow(notification: NSNotification) {
view.frame.origin.y = -getKeyboardHeight(notification: notification)
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.