No Method declared with Objective-C Selector for Notification UIKeyboardWillShowNotification and UIKeyboardWillHideNotification

若如初见. 提交于 2019-12-01 18:58:45

Assign the Selector as below:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil);

And the method to update what you want:

func keyboardWillShow(notification: NSNotification) {

     //Update UI or Do Something

}

Same way you can do for UIKeyboardWillHideNotification.

Swift 3 example:

NotificationCenter.default.addObserver(self, selector: #selector(YourClass.keyboardWillShow(notification:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(YourClass.keyboardWillHide(notification:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil);

// MARK: - Actions

@objc private func keyboardWillShow(notification: Notification) {
    print("keyboardWillShow called")
}

@objc private func keyboardWillHide(notification: Notification) {
    print("keyboardWillHide called")
}

The swift syntax changed. Try this:

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

I have had same issues and also find out that the class you refer on must also be subclassed from NSObject (which is not necc. the case in Swift) Otherwise you get the message

error: argument of '#selector' refers to instance method 'yourMethod(notification:)' that is not exposed to Objective-C"

Swift 3 syntax (just like Sohil's above):

    func someMethod(sender: Any?) {
      ...
    }

    func someBlockCallingWithSelector() {
      someObject.addTarget(self, action: #selector(someMethod), for: .valueChanged) 
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!