我有一个UIView,当键盘出现时它无法正确移动。在UIView中有一个UITextView,我用它来输入文本。如果我选择TextView输入文本,键盘会出现,但是第一次UIView不会移动。如果我点击背景使键盘消失,然后再次点击TextView,那么UIView就会正确地上移。有人知道这里发生了什么吗?
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()
}
}