How to readjust scrollview inset when keyboard is on screen and user selected predictive on/off?

108 Views Asked by At

I have the set up below. It does a good job to move the textFields above the keyboard when the keyboard is on screen. In that very moment, if the user turns off the predictive keyboard, the height is unable to readjust to the new keyboardFrame.height + 20 (extra padding between keyboard and textField). What is a good way to readjust the scrollView.contentInset.bottom when keyboard is on screen and user keeps switching between predictive on/ off?

ViewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notificaiton:)), name: .UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)

Oberservers:

//MARK: Keyboard Notifications 

func keyboardWillShow(notificaiton: Notification) {

    adjustKeyboardHeight(show: true, notification: notificaiton)
}

func keyboardWillHide(notification: Notification) {

    adjustKeyboardHeight(show: false, notification: notification)

}


private func adjustKeyboardHeight(show: Bool, notification: Notification) {

    let userInfo = notification.userInfo!

    let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    if show {

        fgScrollView.contentInset.bottom = keyboardFrame.height + 20
    } else {

        fgScrollView.contentInset = UIEdgeInsets.zero
    }


}

//MARK: TextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == emailTextField {

       nextTextField.becomeFirstResponder()
    }

    textField.resignFirstResponder()

    return true
}
1

There are 1 best solutions below

0
On

Add keyboardWillChangeFrame observer, This oberver will called every time when keyboard frame will change

 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(notificaiton:)), name: .UIKeyboardWillChangeFrame, object: nil)

    func keyboardWillChangeFrame(notificaiton : Notification ) -> Void {

          print("New frame of keyboard = \(notificaiton.userInfo?[UIKeyboardFrameEndUserInfoKey] ?? 0)")  

    }