Search code examples
iosswiftswift3nsnotificationcenterswift4.2

How to write Keyboard notifications in Swift 4.2?


I'm trying to update this code from Swift 3 to Swift 4.2

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: .UIKeyboardDidShow, object: nil);

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

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: .UIResponder.keyboardDidShowNotification, object: nil);

Unfortunately, that doesn't take me far, resulting in additional error: "Type of expression is ambiguous without more context"
Has anyone solved this please? enter image description here


Solution

  • Just replace .UIResponder.keyboardDidShowNotification with UIResponder.keyboardDidShowNotification and it will solve your problem.

    And final code will be:

    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)