1

In the app I am building I have a Textfield with a button at the bottom of my screen, and I want to animate them up when the keyboard appears.

For that I use this:

override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        }

@objc func keyboardWillShow(notification: Notification) {

        let keyboardSize = (notification.userInfo?  [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue

        let keyboardHeight = keyboardSize?.height

        if #available(iOS 12.0, *) {

            self.submitConstraint.constant = (keyboardHeight! - view.safeAreaInsets.bottom) + 10
        }
        else {
            self.submitConstraint.constant = view.safeAreaInsets.bottom + 10
        }

        UIView.animate(withDuration: 0.5){

            self.view.layoutIfNeeded()

        }


    }

@objc func keyboardWillHide(notification: Notification){

        self.submitConstraint.constant = 34 // or change according to your logic

        UIView.animate(withDuration: 0.5){

            self.view.layoutIfNeeded()

        }

    }

but, then a part of the button gets hidden under the suggestions toolbar.

I have googled this, and I found this answer: How to get the height of the keyboard including suggestions bar in swift. I tried the answers, and it didn't work for me, a part of the button still is hidden under the suggestions bar.

Could anybody help me?

Thanks!

BSM
  • 87
  • 2
  • 12
  • It seems to me that instead of making assumptions based on the keyboard height and performing some sort of subtraction or addition, it is better to think about where the keyboard _is_, converted to the coordinates of your view. Also I don't see what the point of measuring against the safe area insets is. – matt Mar 26 '20 at 19:00
  • that part I copied from a diferent answer, that showed how to do it in general, and I jsust changed the numbers – BSM Mar 26 '20 at 19:33

0 Answers0