Keyboard and Notifications

Hello, guys!

Have a problem:


Added observers for keyboardDidShowNotification and keyboardWillHideNotification events:


NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShown(_:)), name: Notification.Name("keyboardDidShowNotification"),object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: Notification.Name("keyboardWillHideNotification"), object: nil)


and made the notifications handling:


@objc func keyboardDidShown (_ aNotification: Notification) {

my code

}


@objc func keyboardWillBeHidden (_ aNotification: Notification) {

my code

}


Keyboard appears when I begin to edit text field but keyboardDidShown and keyboardWillBeHidden functions don't work at all (I did breakpoint right after @objc func keyboardDidShown (_ aNotification: Notification) { ).


What's the problem?

Accepted Reply

When you say it does not work, you mean it is not called ?


If so, could be that notification name is incorrect.



Change

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShown(_:)), name: Notification.Name("keyboardDidShowNotification"),object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: Notification.Name("keyboardWillHideNotification"), object: nil)

with:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShown(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification), object: nil)

Replies

When you say it does not work, you mean it is not called ?


If so, could be that notification name is incorrect.



Change

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShown(_:)), name: Notification.Name("keyboardDidShowNotification"),object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: Notification.Name("keyboardWillHideNotification"), object: nil)

with:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShown(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification), object: nil)

Thanks a lot, Claude31!

Now it works!