I have a UIView that isn't moving properly when the keyboard appears. There is a UITextView in a UIView that I use to enter text. If I select the TextView to enter text, the keyboard appears but the UIView doesn't move THE FIRST TIME. If I tap the background and make the keyboard disappear and then tap on the TextView again, then the UIView moves up properly. Does anyone know what's happening here?
class ChatViewController: UIViewController, CNContactPickerDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UIToolbarDelegate, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var composeTextView: UITextView!
@IBOutlet weak var composeViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
composeTextView.delegate = self
}
func textViewDidBeginEditing(_ textView: UITextView) {
UIView.animate(withDuration: 0.5){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
self.view.layoutIfNeeded()
}
@objc func keyboardWillShow(notification: Notification) {
let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let keyboardHeight = keyboardSize?.height
if #available(iOS 11.0, *){
self.composeViewBottomConstraint.constant = keyboardHeight! - view.safeAreaInsets.bottom
}
else {
self.composeViewBottomConstraint.constant = view.safeAreaInsets.bottom
}
self.view.layoutIfNeeded()
}
}
The problem is that the view not going up in first click of the textView is that the showKeyboard observer is added in beginEditing , so this line should be in viewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
in addition to the following fixes
func textViewDidBeginEditing(_ textView: UITextView) {
// I think no need for it
}
@objc func keyboardWillShow(notification: Notification) {
let keyboardSize = (notification.userInfo? [UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let keyboardHeight = keyboardSize?.height
if #available(iOS 11.0, *){
self.composeViewBottomConstraint.constant = keyboardHeight! - view.safeAreaInsets.bottom
}
else {
self.composeViewBottomConstraint.constant = view.safeAreaInsets.bottom
}
UIView.animate(withDuration: 0.5){
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHide(notification: Notification){
self.composeViewBottomConstraint.constant = 0 // or change according to your logic
UIView.animate(withDuration: 0.5){
self.view.layoutIfNeeded()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With