首页 > 解决方案 > 应用程序崩溃:异常 - 无法识别的选择器发送到实例

问题描述

一旦键盘像这样切换,我有一个 UITableviewController 具有以下逻辑来向上/向下滑动整个视图:

class ChatDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 // variables...

 override func viewDidLoad() {
        super.viewDidLoad()
        // do stuff...
        NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillShow:")), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillHide:")), name: UIResponder.keyboardWillHideNotification, object: nil)
       // do other stuff...
}
...
func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

    func keyboardWillHide(notification: NSNotification) {
        self.view.frame.origin.y = 0
    }
...
}

切换键盘然后使应用程序崩溃,并出现以下异常: ChatDetailViewController keyboardWillShow:]: unrecognized selector sent to instance 0x7f82fc41fdf0

乍一看,错误消息似乎很清楚,但我仍然无法弄清楚我的选择器出了什么问题。没有代码警告,没有错别字,...

我在这里做错了什么?

标签: swiftnsnotificationcenter

解决方案


在 Swift 4 中,我以前曾这样使用过

override func viewDidLoad() {
    super.viewDidLoad()   
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
     print("keyboardWillShow")
}

@objc func keyboardWillHide(notification: NSNotification){
     print("keyboardWillHide")
}

在 Swift 5 中,他们重命名了访问键盘通知的方式UIResponder

override func viewDidLoad() {
    super.viewDidLoad()   
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

推荐阅读