4

I have screen with scrollView and bottomContainerView with two textFields and two buttons. And I want to scrollView scroll to bottom when keyboard was shown. 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). And in iOS 11.4 it works. But in iOS 12 doesn't.

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 12.0

enter image description here

1 Answers1

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

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

Regards

mfiore
  • 321
  • 3
  • 16