应用程序崩溃:异常 - 无法识别的选择器发送到实例 [英] App crashing: Exception - unrecognised selector sent to instance
问题描述
我有一个带有以下逻辑的 UITableviewController,一旦键盘像这样切换,就可以向上/向下滑动整个视图:
I've got a UITableviewController with following logic to slide up / down the entire view once the keyboard toggles like so:
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
Toggling the keyboard then crashes the App with following exception: ChatDetailViewController keyboardWillShow:]: unrecognized selector sent to instance 0x7f82fc41fdf0
错误消息乍一看似乎很清楚,但我仍然无法弄清楚我的选择器出了什么问题.没有代码警告,没有错别字,...
The error message seems clear at first glance but I still can't figure out what's wrong with my selector. No code warnings, no typos,...
我在这里做错了什么?
推荐答案
三个问题:
- 选择器的创建有误(使用
#selector
) - 动作的签名错误(缺少下划线)
- 动作必须标记为
@objc
Swift 中的类型是 Notification
没有 NS
前缀
And the type in Swift is Notification
without NS
prefix
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...
}
...
@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
}
...
这篇关于应用程序崩溃:异常 - 无法识别的选择器发送到实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!