RubberDucky4444 RubberDucky4444 - 6 months ago 193
Swift Question

Swift 3 NSNotificationCenter Keyboardwillshow/hide

I have a piece of code that worked in Swift 2 and i tried using xCode to update the code to the newest version and i fixed everything except two issues

I have this code

NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)

that pairs along with this

func keyboardWillShow(notification: NSNotification) {

constraint.constant = -100
UIView.animate(withDuration: 0.3) {

func keyboardWillHide(notification: NSNotification) {

constraint.constant = 25
UIView.animate(withDuration: 0.3) {

On the first part I now get an error saying "Type 'LoginViewController' has no member 'keyboardwillshow/hide'

I don't understand why it is not seeing the method underneath

Does anybody know a solution to this issue?


Check out the updated Swift Programming Language book. Pages 1027 and 1028 are what you're looking for. It should be something like this:

func keyboardWillHide(_ notification: NSNotification) {…

Notice the additional underscore above. Also:


You also might need to add @objc(keyboardWillHideWithNotification:) to your class.