swift - 应用程序崩溃:异常 - 无法识别的选择器发送到实例
问题描述
一旦键盘像这样切换,我有一个 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
乍一看,错误消息似乎很清楚,但我仍然无法弄清楚我的选择器出了什么问题。没有代码警告,没有错别字,...
我在这里做错了什么?
解决方案
在 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)
}
推荐阅读
- javascript - 如何在 Redux 的状态中保存用户条目?
- oracle - 纪元转换减少 1 秒
- azure-web-app-service - 执行双向 TLS 时限制接受的客户端证书的数量
- php - 异步重新验证 joomla 3
- android - 我应该支付谷歌地图在 android 应用程序中发出 GPS 坐标请求吗?
- selenium - 在 Selenium 中按住鼠标右键和中键
- javascript - 将缓存值发送到浏览器保存密码字段
- field - $_POST 不适用于 Bluesnap 托管付款字段
- java - 减少代码行和使用可选的最佳方式
- javascript - 如何使chartjs中的饼图可点击(react-native)