我正在尝试在KeyboardScrollController
课程中获取键盘通知,但我为UIKeyboardWillHideNotification
和UIKeyboardDidShowNotification
设置了无法识别的选择器。
这是我的简单实现:
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)
{
}
}
但每次出现键盘时都会出现此错误:
*** NSForwarding:警告:类'KeyboardScrollController'的对象0x7fdc8d882730没有实现methodSignatureForSelector: - 提前出现问题 无法识别的选择器 - [KeyboardScrollController keyboardWillHide:]
我尝试了Selecor("keyboardWillHide:")
,但这没有任何区别。
这里有什么问题?我已经在Objective-C中多次实现了这个,但我无法在Swift中使用它。
答案 0 :(得分:1)
NSObject
才能使其发挥作用:
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)
{
}
}