user3362882 user3362882 - 6 months ago 38
Swift Question

How to make UITextField move up when keyboard is present?

How do I prevent a

UITextField
from being hidden by the keyboard?

Answer

I assume this is happening on a UIViewController. If so, you can setup the following 2 functions to be called when the keyboard will show/hide, and respond appropriately in their blocks.

Setting up the UIViewController:

class XXXViewController: UIViewController, UITextFieldDelegate... {

    var frameView: UIView!

First, in ViewDidLoad:

override func viewDidLoad() {

    self.frameView = UIView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height))


    // Keyboard stuff.
    let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
        center.addObserver(self, selector: #selector(ATReportContentViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
    center.addObserver(self, selector: #selector(ATReportContentViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}

Then implement the following 2 functions to respond to your NSNotificationCenter functions defined in ViewDidLoad above. I give you an example of moving the entire view, but you can also animate just the UITextFields.

func keyboardWillShow(notification: NSNotification) {
    let info:NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    let keyboardHeight: CGFloat = keyboardSize.height

    let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat


    UIView.animateWithDuration(0.25, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
        self.frameView.frame = CGRectMake(0, (self.frameView.frame.origin.y - keyboardHeight), self.view.bounds.width, self.view.bounds.height)
        }, completion: nil)

}

func keyboardWillHide(notification: NSNotification) {
    let info: NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    let keyboardHeight: CGFloat = keyboardSize.height

    let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat

    UIView.animateWithDuration(0.25, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
        self.frameView.frame = CGRectMake(0, (self.frameView.frame.origin.y + keyboardHeight), self.view.bounds.width, self.view.bounds.height)
        }, completion: nil)

}

Don't forget to remove the notifications if you leave your view

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}