There is no method declared using Objective-C Selector to notify UIKeyboardWillShowNotification and UIKeyboardWillHideNotification

After a recent Xcode update, this code that used to work no longer works. Most of the selector (":") has auto-correction with an 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 indicates an error:

No method is declared using the Objective CWillSHow selector keypad: '

This image shows different attempts that all failed.

enter image description here

What is the new syntax for this code?

+5
source share
5 answers

Assign a Selector as shown below:

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

And the update method of what you want:

 func keyboardWillShow(notification: NSNotification) { //Update UI or Do Something } 

The same can be done for UIKeyboardWillHideNotification .

+10
source

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") } 
+1
source

Quick syntax changed. Try the following:

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

I had the same problems, and it also turned out that the class you are referring to must also be subclassed from NSObject (which is not necessary in the case of Swift). Otherwise you will receive a message

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

Swift 3 syntax (like Sohil above):

  func someMethod(sender: Any?) { ... } func someBlockCallingWithSelector() { someObject.addTarget(self, action: #selector(someMethod), for: .valueChanged) } 
0
source

Source: https://habr.com/ru/post/1246270/


All Articles