我有带有带有两个textFields和两个按钮的scrollView和bottomContainerView的屏幕。我想在显示键盘时将scrollView滚动到底部。这就是为什么我首先设置scrollView.contentOffset,然后尝试使forgetButton的框架可见(将所有视图滚动到底部)的原因。并且在iOS 11.4中可以正常工作。但是在iOS 12中却没有。
private func adjustInsetForKeyboardShow(_ show: Bool, notification: Notification) {
let userInfo = notification.userInfo ?? [:]
if let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let adjustmentHeight = (keyboardFrame.height + 24) * (show ? 1 : 0)
scrollView.contentInset.bottom = adjustmentHeight
scrollView.scrollIndicatorInsets.bottom = adjustmentHeight
// set offset
let top = bottomContainerView.frame.minY + forgetButton.frame.minY
let height = forgetButton.frame.height
scrollView.scrollRectToVisible(CGRect(x: 0, y: top, width: 1, height: height), animated: true)
}
}
@objc
private func keyboardWillShow(_ notification: Notification) {
adjustInsetForKeyboardShow(true, notification: notification)
}
@objc
private func keyboardWillHide(_ notification: Notification) {
adjustInsetForKeyboardShow(false, notification: notification)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
}
iOS 11.4
iOS 12.0
答案 0 :(得分:0)
您可以尝试更改此部分:
let userInfo = notification.userInfo!
let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
或者:在View的底部创建一个约束,然后在打开键盘时向其添加键盘的高度尺寸(keyboardFrame.height),并使用动画更新约束
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
致谢