How to move uitextfield up when keyboard appears

 

This tutorial has been updated for X code 7.3 & swift 2.2

Many times you have textfield at bottom of view controller. And when you start editing textfield the keyboard covers textfield and you cannot see what you are typing. This also happens when you change the phone orientation. Today we are going to fix both of these problems.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to move textfield & save it on desktop.

new x code project

 

2. Go to main storyboard & add textfield at the bottom of view controller

new textfield

3. Set constraints to left, right & bottom edges of view controller for 20 points

textfield with constraint

4. Connect bottom constraint as outlet to swift file

bottom constraint as outlet

 

5. In view did load add following code to create notification of when keyboard will appear & disappear

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)

    // Do any additional setup after loading the view, typically from a nib.
}

6. Now create methods that get triggered by notification

func keyboardWillShow(notification:NSNotification) {

}

func keyboardWillHide(notification:NSNotification) {

}

7. We will create helper function to reduce repeating of code

func adjustingHeight(show:Bool, notification:NSNotification) {
    // 1
    var userInfo = notification.userInfo!
    // 2
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
    // 3
    let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
    // 4
    let changeInHeight = (CGRectGetHeight(keyboardFrame) + 40) * (show ? 1 : -1)
    //5
    UIView.animateWithDuration(animationDurarion, animations: { () -> Void in
        self.bottomConstraint.constant += changeInHeight
    })

}
  1. Get notification information in an dictionary
  2. From information dictionary get keyboard’s size
  3. Get the time required for keyboard pop up animation
  4. Extract height of keyboard & add little space(40) between keyboard & text field. If bool is true then height is multiplied by 1 & if its false then height is multiplied by –1. This is short hand of if else statement. See complete list of short hand here.
  5. Animation moving constraint at same speed of moving keyboard & change bottom constraint accordingly.

8. Now add instance of this function in both notification methods

func keyboardWillShow(notification:NSNotification) {
    adjustingHeight(true, notification: notification)
}

func keyboardWillHide(notification:NSNotification) {
    adjustingHeight(false, notification: notification)
}

9. This is optional but when you have multiple views then remove the observer notification after closing view.

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

10. Add following method to close keyboard when touched on empty area

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}

See different ways to close keyboard after editing here.
Now build and run app in iPhone 5s. Edit text field and close by tapping on empty area

move textfield

Now change the orientation & test the textfield

landscape move textfield
Download X code file
Challenge 1: Add multiple textfield in view controller & move them only if they get covered by textfield.

multiple move textfield

Challenge 2: Change orientation & get same result as challenge 1

landscape multiple move textfield
Download Challenge Solution

Total 40 Votes
23

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?