最近更新Xcode之后,以前工作的代码不再有效。大多数选择器(":")都有自动更正,但此代码除外:
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);
}
标记错误:
没有使用Objective C选择器声明的方法' keyboardWillSHow:'
此图片显示了所有失败的尝试。
此代码的新语法是什么?
答案 0 :(得分:11)
分配Selector
,如下所示:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil);
更新所需内容的方法:
func keyboardWillShow(notification: NSNotification) {
//Update UI or Do Something
}
您可以对UIKeyboardWillHideNotification
执行相同的操作。
答案 1 :(得分:1)
Swift 3示例:
<div id="target"></div>
答案 2 :(得分:0)
swift语法改变了。试试这个:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(ClassThatHasTheSelector.keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil);
答案 3 :(得分:0)
我遇到了同样的问题,并且还发现你所引用的类也必须是 NSObject 的子类(这不是necc。在Swift中的情况)否则你会得到消息
error: argument of '#selector' refers to instance method 'yourMethod(notification:)' that is not exposed to Objective-C"
答案 4 :(得分:0)
Swift 3语法(就像上面的Sohil一样):
func someMethod(sender: Any?) {
...
}
func someBlockCallingWithSelector() {
someObject.addTarget(self, action: #selector(someMethod), for: .valueChanged)
}