我似乎找不到我做的功能。
错误:类型'ChatViewController'没有成员'showOrHideKeyboard'
代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.defaultCenter.addObserver(self, selector: #selector(ChatViewController.showOrHideKeyboard(_:)), name: UIKeyboardWillShowNotification, object: nil)
NotificationCenter.defaultCenter.addObserver(self, selector: #selector(ChatViewController.showOrHideKeyboard(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
@IBOutlet weak var contraintToBottom: NSLayoutConstraint!
func showOrHideKeyboard(notification: NSNotification) {
if let keyboardInfo: Dictionary = notification.userInfo {
if notification.name == UIResponder.keyboardWillShowNotification {
UIView.animate(withDuration: 1, animations: { () in
self.contraintToBottom.constant = (keyboardInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
self.view.layoutIfNeeded()
}) { (completed: Bool) -> Void in
//
}
}
}
}
答案 0 :(得分:2)
您应将选择器方法标记为objc
更改此行
func showOrHideKeyboard(notification: NSNotification) {
}
此行
@objc func showOrHideKeyboard(_ notification: NSNotification) {
}
答案 1 :(得分:0)
使用以下任一方法:
@objc func showOrHideKeyboard(_ notification: NSNotification)
#selector(ChatViewController.showOrHideKeyboard(_:))
或者:
@objc func showOrHideKeyboard(notification: NSNotification) {
#selector(ChatViewController.showOrHideKeyboard(notification:))
请注意函数签名中的_
和#selector
。
答案 2 :(得分:0)
在最新版本的快速版本中,似乎不再支持带有函数名称但不带参数名称“(_ :)”的#selector。
只需替换填充arg名称或使用自动完成功能即可键入声明:
#selector(ViewController.showOrHideKeyboard(notification:)
答案 3 :(得分:0)
按如下所示优化代码
在ViewDidLoad()
[NSNotification.Name.UIKeyboardWillShow,
NSNotification.Name.UIKeyboardWillHide].forEach { (notificationName) in
NotificationCenter.default.addObserver(self, selector: #selector(notificationObservered(notification:)),
name: notificationName, object: nil)
}
创建函数
// MARK: - Notification Observered
/// Notification received
@objc func notificationObservered(notification: NSNotification) {
switch notification.name {
case NSNotification.Name.UIKeyboardWillShow:
break
case NSNotification.Name.UIKeyboardWillHide:
// let info = notification.userInfo!
// let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
break
default:
break
}
}