出现时,我需要在键盘上移动文本字段。
我正在使用以下代码:
override func viewDidLoad() {
super.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)
}
接着:
@objc func keyBoardWillShow(_ notification: NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
UIView.animate(withDuration: 0.4) {
self.commentViewBottomConstraint.constant = keyboardHeight
self.view.layoutIfNeeded()
}
}
@objc func keyBoardWillHide(_ notification: NSNotification) {
UIView.animate(withDuration: 0.4) {
self.commentViewBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
问题是似乎键盘高度不正确。实际上,视图的底部与键盘不对齐。视图和键盘之间有一个空间。
老实说我不明白我在做什么错...
感谢您的帮助!
最佳答案
我认为问题在于事实是底部约束相对于安全区域。
所以我通过添加以下内容修复了它:
let safeAreaHeight = self.view.safeAreaInsets.bottom
self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight
这是完整的代码:
@objc func keyBoardWillShow(_ notification: NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
let safeAreaHeight = self.view.safeAreaInsets.bottom
UIView.animate(withDuration: 0.4) {
self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight
self.view.layoutIfNeeded()
}
}