How to write Keyboard notifications in Swift 3

ICL1901 picture ICL1901 · Jun 17, 2016 · Viewed 44.1k times · Source

I'm trying to update this code to swift 3:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)`

So far, I've just tried the auto corrections given by the compiler. This results in code like this:

let notificationCenter = NotificationCenter.default()
notificationCenter.addObserver(self, selector: Selector(("keyboardWillShow:")), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

notificationCenter.addObserver(self, selector: Selector(("keyboardWillHide:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)`

Unfortunately, that doesn't take me far, resulting in additional errors.

Has anyone solved this please?

Please note that I'm just trying how to write the notifications. I'm not (yet) trying to fix the notification functions.. Thanks

Answer

fssilva picture fssilva · Jul 24, 2018

Swift 4.2 Xcode 10 (10L213o)

The main changes compared with Swift 3 are in the UIWindow.keyboardWillShowNotification and UIWindow.keyboardWillHideNotification

let notifier = NotificationCenter.default
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)),
                     name: UIWindow.keyboardWillShowNotification,
                     object: nil)
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)),
                     name: UIWindow.keyboardWillHideNotification,
                     object: nil)


@objc
func keyboardWillShowNotification(_ notification: NSNotification) {}

@objc
func keyboardWillHideNotification(_ notification: NSNotification) {}