No Method declared with Objective-C Selector for N

2019-02-22 16:55发布

After the recent update of Xcode, this code that used to work no longer works. Most of the Selector(":") has an auto correction with the exception for this code:

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

which flags an error:

No method declared with Objective C selector 'keyboardWillSHow:'

This image show different attempts which have all failed.

enter image description here

What is the new syntax for this code?

5条回答
看我几分像从前
2楼-- · 2019-02-22 17:32

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")
}
查看更多
Luminary・发光体
3楼-- · 2019-02-22 17:32

The swift syntax changed. Try this:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(ClassThatHasTheSelector.keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil);
查看更多
Explosion°爆炸
4楼-- · 2019-02-22 17:32

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"
查看更多
地球回转人心会变
5楼-- · 2019-02-22 17:44

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.

查看更多
SAY GOODBYE
6楼-- · 2019-02-22 17:46

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

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

    func someBlockCallingWithSelector() {
      someObject.addTarget(self, action: #selector(someMethod), for: .valueChanged) 
    }
查看更多
登录 后发表回答