【发布时间】:2021-06-25 09:59:56
【问题描述】:
我希望实现键盘和视图调整大小的行为,如 iOS 消息中所示。它看起来像
https://i.imgur.com/92rvHpo.mp4
我尝试以下方法
步骤 1
这确保了当我们的向下滚动手势触及键盘区域时,键盘将随着我们的手势动作向下滚动。
collectionView.keyboardDismissMode = .interactive
第二步
调整底部约束,以确保我们的集合视图不会被键盘在视觉上阻挡。当键盘完成隐藏或键盘显示完成时,我们调整底部约束。
override func viewDidLoad() {
super.viewDidLoad()
initKeyboardNotifications()
}
//
// https://stackoverflow.com/a/41808338/72437
//
func initKeyboardNotifications() {
// If your app targets iOS 9.0 and later or macOS 10.11 and later, you do not need to unregister an observer
// that you created with this function.
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc private func keyboardWillShow(sender: NSNotification) {
let i = sender.userInfo!
let s: TimeInterval = (i[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let k = (i[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
bottomLayoutConstraint.constant = -k
UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}
@objc private func keyboardWillHide(sender: NSNotification) {
let info = sender.userInfo!
let s: TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
bottomLayoutConstraint.constant = 0
UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}
到目前为止,这是我们不完美的结果。
我想,当键盘被拖动时,我需要实时调整底部约束。但是,我不知道从哪里可以得到键盘高度信息,当它被拖动时。
您知道如何在拖动键盘时实时调整底部约束吗?
【问题讨论】: