How to write Keyboard notifications in Swift 3
Swift 4.2 Xcode 10 (10L213o)
The main changes compared with Swift 3 are in the UIWindow.keyboardWillShowNotification
and UIWindow.keyboardWillHideNotification
let notifier = NotificationCenter.defaultnotifier.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)), name: UIWindow.keyboardWillShowNotification, object: nil)notifier.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)), name: UIWindow.keyboardWillHideNotification, object: nil)@objcfunc keyboardWillShowNotification(_ notification: NSNotification) {}@objcfunc keyboardWillHideNotification(_ notification: NSNotification) {}
Swift 4
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)}func keyboardWillShow(notification: NSNotification) { print("keyboardWillShow")}func keyboardWillHide(notification: NSNotification){ print("keyboardWillHide")}deinit { NotificationCenter.default.removeObserver(self)}
You can also get keyboard info using below code inside these methods.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil) . @objc func keyboardWillChange(notification: NSNotification) { let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let deltaY = targetFrame.origin.y - curFrame.origin.y }
I fixed this issue by writing the code like this
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)