Skip to main content

Solving the problem UITextField getting hidden by the keyboard.

We need to know the timing of the keyboard showing up so that we can slide the view up, for that we have the NSNotificationCenter: 

NotificationCenter.default.addObserver( selfselector: #selector( keyboardWillShow ), name: UIResponder.keyboardWillShowNotificationobject: nil )

So basically what this does is that it sets an observer to tell us when the keyboard is about to show. 

In other words, it is as if our view controller is signing up to be notified when an event is coming up.

In the code written above, when the viewController is notified of the keyboard showing, we want it to execute the function: keyboardWillShow()

@objc func keyboardWillShow( _ notification: Notification ){

        self.view.frame.origin.y = -getKeyboardHeight( notification )

}

What this function is doing is to simply shifting the view up by a distance that equals the hight of the keyboard.

NSNotifications carry information in a userInfo dictionary. In this case we are using the keyboardWillShowNotification which carries the keyboard frame in its userInfo dictionary. So we do the following to get the keyboard height: 

func getKeyboardHeight_ notification: Notification ) -> CGFloat {

        let userInfo = notification.userInfo

        let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKeyasNSValue

        return keyboardSize.cgRectValue.height

}

The full implementation is written in the following Gist: UITextFieldHiddenByKeyboard

Comments