Mateo Villagomez Mateo Villagomez - 3 months ago 22
Swift Question

How to use Objective C selectors as arguments when subscribing to NSNotifications?

I have the following subscription in swift. I need to know when the keyboard will show to move the view up. It compiles and works as expected but I don't know how to get rid of this warning. "No method declared with Objective-C selector'keyboardWillShow'"

// Subscribing class to recieve the notification
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow", name: UIKeyboardWillShowNotification, object: nil)
}
// Shifting view's frame up
func keyboardWillShow(notification: NSNotification) {
view.frame.origin.y -= getKeyboardHeight(notification)
}
// Getting keyboard height
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.CGRectValue().height
}


Thanks in advanced for any suggestions!

JAL JAL
Answer

Use #selector:

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