1

Here is my function for adding an observer

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}

but .UIKeyboardWillShow is giving me an error

'UIKeyboardWillShow' has been renamed to 'UIResponder.keyboardWillShowNotification'

Replace 'UIKeyboardWillShow' with 'UIResponder.keyboardWillShowNotification'

but when I replace it

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIResponder.keyboardWillShowNotification, object: nil)
}

I get this error

Type of expression is ambiguous without more context

  • You need to remove the `.` before `UIResponder`. https://stackoverflow.com/questions/52316676/type-nsnotification-name-has-no-member-keyboarddidshownotification/52325564#52325564 – Rakesha Shastri Sep 17 '18 at 13:03
  • Possible duplicate of [Type 'NSNotification.Name' has no member 'keyboardDidShowNotification'](https://stackoverflow.com/questions/52316676/type-nsnotification-name-has-no-member-keyboarddidshownotification) – Rakesha Shastri Sep 17 '18 at 13:04
  • And you need to import UIKit module not Foundation – Dimitar Stefanovski May 17 '19 at 08:41

4 Answers4

5

Without a dot

NotificationCenter.default.addObserver(self, 
selector: #selector(keyboardWillShow), 
name: UIResponder.keyboardWillShowNotification, object: nil)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0
let notificationCenter = NotificationCenter.default

notificationCenter.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillShow(notification: notification)
            }
notificationCenter.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillHide(notification: notification)
            }
Shanice Ho
  • 11
  • 3
0

Just import module UIKit because UIResponder is part of UIKit not Foundation module

SWIFT 5 CODE

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addObservers()
    }

    public func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    }

    @objc func handleKeyboardWillShow(_: Notification) {
        // Here handle keyboard
    }
}
-1

I have used this, and working perfectly fine

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowOrHide(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
Mehul Thakkar
  • 12,440
  • 10
  • 52
  • 81