【发布时间】:2018-09-01 15:11:00
【问题描述】:
当键盘出现时,我的 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()
}
}
【问题讨论】:
-
嗨,坏人,你想要的是当键盘出现时向上移动 UIView,当键盘消失时向下移动。
-
是的,是的,列宁。
标签: ios swift constraints