API has changed a little bit with Swift 4.2
. You need to do something similar to this.
//inside 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)
then we'll have to the supporting functions. Since we are involving selectors (which is part of Objective C stuff) we need to use @objc
prefix with our functions.
@objc func keyboardWillShow(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
}
@objc func keyboardWillHide(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
if you have a different name for your UITableView
then change the variable tableView
inside the function.
Also, if you want to hide the keyboard when the user touches outside the TextView or TextField then do the following.
//inside the viewDidLoad
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
and implement the function given in the selector as below
@objc func dismissKeyboard() {
view.endEditing(true)
}