简体   繁体   English

在iOS 12上的scrollView.contentInset之后,scrollView.setContentOffset不起作用

[英]scrollView.setContentOffset doesn't work after scrollView.contentInset on iOS 12

I have screen with scrollView and bottomContainerView with two textFields and two buttons. 我有带有scrollView和bottomContainerView的屏幕,带有两个textFields和两个按钮。 And I want to scrollView scroll to bottom when keyboard was shown. 我想在显示键盘时将scrollView滚动到底部。 That is why I firstly set scrollView.contentOffset and then I am trying to make frame of forgetButton visible(to scroll all view to bottom). 这就是为什么我首先设置scrollView.contentOffset然后我试图使forgetButton框架可见(将所有视图滚动到底部)。 And in iOS 11.4 it works. 在iOS 11.4中它可以工作。 But in iOS 12 doesn't. 但在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 11.4

iOS 11.4

iOS 12.0 iOS 12.0

在此输入图像描述

You can try to change this part: 您可以尝试更改此部分:

let userInfo = notification.userInfo!
let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect

Alternatively: create a constraint with the bottom of the View, and when the keyboard is open add to the contraint the height dimension of the keyboard (keyboardFrame.height), and update the constraint with animations 或者:使用视图底部创建约束,并在键盘打开时向键盘添加键盘的高度尺寸(keyboardFrame.height),并使用动画更新约束

 UIView.animate(withDuration: 0.3) {
  self.view.layoutIfNeeded()
 }

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM