5

在最近更新 Xcode 之后,以前可以工作的代码不再工作了。大多数 Selector(":") 具有自动更正功能,但以下代码除外:

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:”声明的方法

此图像显示了所有失败的不同尝试。

在此处输入图像描述

这段代码的新语法是什么?

4

5 回答 5

11

分配Selector如下:

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

以及更新您想要的方法:

func keyboardWillShow(notification: NSNotification) {

     //Update UI or Do Something

}

同样的方式你可以为UIKeyboardWillHideNotification.

于 2016-04-02T07:53:29.723 回答
2

斯威夫特 3 示例:

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")
}
于 2016-11-21T13:31:48.047 回答
0

swift 语法发生了变化。试试这个:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(ClassThatHasTheSelector.keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil);
于 2016-04-01T21:32:18.200 回答
0

我遇到了同样的问题,并且还发现您引用的类也必须是NSObject的子类(这不是必需的。Swift 中的情况)否则您会收到消息

error: argument of '#selector' refers to instance method 'yourMethod(notification:)' that is not exposed to Objective-C"
于 2016-09-29T09:23:40.843 回答
0

Swift 3 语法(就像上面的 Sohil 一样):

    func someMethod(sender: Any?) {
      ...
    }

    func someBlockCallingWithSelector() {
      someObject.addTarget(self, action: #selector(someMethod), for: .valueChanged) 
    }
于 2016-10-03T02:06:21.497 回答