问题描述:

I am trying to get keyboard notificaitons in my KeyboardScrollController class, but I get unrecognized selector for UIKeyboardWillHideNotification and UIKeyboardDidShowNotification.

This is my simple implementation:

public class KeyboardScrollController

{

public func subscribeForKeyboardNotifications()

{

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

}

public func unsubscribeForKeyboardNotifications()

{

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil);

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil);

}

//MARK: Keyboard events

public func keyboardWasShown(notification: NSNotification)

{

}

public func keyboardWillHide(notification: NSNotification)

{

}

}

But every time the keyboard should be presented it crashes with this error:

*** NSForwarding: warning: object 0x7fdc8d882730 of class 'KeyboardScrollController' does not implement methodSignatureForSelector: -- trouble ahead

Unrecognized selector -[KeyboardScrollController keyboardWillHide:]

I have tried with Selecor("keyboardWillHide:"), but that did not make any difference.

What is wrong here? I have implemented this several times in Objective-C, but I cannot make it work in Swift.

网友答案:

Ah, it suddenly hit me, what the issue could be. I had to inherit from NSObject to make it work:

public class KeyboardScrollController : NSObject
{
    public func subscribeForKeyboardNotifications()
    {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
    }

    public func unsubscribeForKeyboardNotifications()
    {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil);
    }

    //MARK: Keyboard events
    public func keyboardWasShown(notification: NSNotification)
    {

    }

    public func keyboardWillHide(notification: NSNotification)
    {

    }
}
相关阅读:
Top