应用程序崩溃:异常-无法识别的选择器发送到实例

我有一个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:]:无法识别的选择器发送到实例0x7f82fc41fdf0

该错误消息乍一看似乎很清楚,但是我仍然不知道选择器有什么问题。没有代码警告,没有错别字,...

我在做什么错了?

landing1984 回答:应用程序崩溃:异常-无法识别的选择器发送到实例

在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,name: UIResponder.keyboardWillShowNotification,name: UIResponder.keyboardWillHideNotification,object: nil)
}
,

您忘记添加@objc部分:

NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillShow),object: nil)
        NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillHide),object: nil)
@objc func keyboardWillShow(_ sender: Notification) {}
@objc func keyboardWillHide(_ sender: Notification) {}

,

三个问题:

  • 选择器的创建错误(使用#selector
  • 动作签名错误(下划线缺失)
  • 该操作必须标记为@objc

Swift中的类型为Notification,不带前缀NS

override func viewDidLoad() {
    super.viewDidLoad()
    // do stuff...
    NotificationCenter.default.addObserver(self,object: nil)
    // do other stuff...
}

    ...

@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.view.frame.origin.y -= keyboardSize.height
    }
}

@objc func keyboardWillHide(_ notification: Notification) {
    self.view.frame.origin.y = 0
}

...
本文链接:https://www.f2er.com/2757617.html

大家都在问