Reputation: 29
I can't seem to find the function I made.
Error: Type 'ChatViewController' has no member 'showOrHideKeyboard'
Code:
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
//
}
}
}
}
Upvotes: 1
Views: 90
Reputation: 2962
Optimise your code like below
In ViewDidLoad()
[NSNotification.Name.UIKeyboardWillShow,
NSNotification.Name.UIKeyboardWillHide].forEach { (notificationName) in
NotificationCenter.default.addObserver(self, selector: #selector(notificationObservered(notification:)),
name: notificationName, object: nil)
}
Create a function
// 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
}
}
Upvotes: 0
Reputation: 37
It seems that #selector with function name but no arguments name "(_:)" is no longer supported in swift lastest versions.
Just replace fill the arg name or use autocomplete to type the declaration:
#selector(ViewController.showOrHideKeyboard(notification:)
Upvotes: 0
Reputation: 11233
Use either this:
@objc func showOrHideKeyboard(_ notification: NSNotification)
#selector(ChatViewController.showOrHideKeyboard(_:))
Or:
@objc func showOrHideKeyboard(notification: NSNotification) {
#selector(ChatViewController.showOrHideKeyboard(notification:))
Notice the _
in function signature and #selector
.
Upvotes: 0
Reputation: 397
You should mark the selector method with objc
Change this line
func showOrHideKeyboard(notification: NSNotification) {
}
to this line
@objc func showOrHideKeyboard(_ notification: NSNotification) {
}
Upvotes: 2