Swift – Moving UITextField up when keyboard is shown

Unlike in Android, where the device keyboard automatically handles display management when it pops up, iOS does not have this capability. So as a programmer, if your form is going to be hidden partially by the keyboard showing up, you have to handle it in code, so that the current UITextField remains visible .

Given below is an example screen, in which the last field, Verify Password, will get hidden behind the keyboard. when the user puts focus in that field. Using the code below, the Verify Password field is moved up and then moved back to its original position when they keyboard retracts.

IMG_0189

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

IMG_0190

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

IMG_0191

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

To do this we need to set bottom constraints for the two UITextFields – Password and Verify Password . In the View Controller we track the original bottom constraints of the two fields. We then hook the two events:

UIKeyboardDidShowNotification

UIKeyboardDidHideNotification

Whenever the KeyboardDidShow notification fires, we check if the current field is either of the password fields. If it is not then, we do not do anything. If it is, then we call a method to manipulate the position of the two password fields.

Given below is the relevant code which does the above. Note that the complete code for the ViewController is not given, so you can just put in the relevant code, wherever required in your project.

class ViewController: UIViewController, UINavigationControllerDelegate, UITextFieldDelegate {

   var origBottomConstraintForPwd:CGFloat = 0
    var origBottomConstraintForPwd2:CGFloat = 0
    var needtoAdjustForKeyboard = false
    var currTextField:UITextField = UITextField()


    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector:         "keyboardDidShow:", name:UIKeyboardDidShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name:UIKeyboardDidHideNotification, object: nil);

    }

    func keyboardDidShow(sender: NSNotification) {
        if needtoAdjustForKeyboard == true {
            adjustingHeight(true, notification: sender)
        }
    }
    
    
    func keyboardDidHide(sender: NSNotification) {
        if needtoAdjustForKeyboard == true {
            adjustingHeight(false, notification: sender)
        }
    }
    
  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) + 10) * (show ? 1 : -1)
        //5
        UIView.animateWithDuration(animationDurarion, animations: { () -> Void in
            if (show && changeInHeight > self.bottomConstraint.constant) {
                if self.currTextField == self.textPwd {
                    self.origBottomConstraintForPwd = self.bottomConstraint.constant
                    self.bottomConstraint.constant += (changeInHeight - self.bottomConstraint.constant )
                }
                else if self.currTextField == self.textPwd2 {
                    self.origBottomConstraintForPwd2 = self.bottomConstraint2.constant
                    self.bottomConstraint2.constant += (changeInHeight - self.bottomConstraint2.constant )
                }
                
            } else if (!show) {
                if self.currTextField == self.textPwd {
                    self.bottomConstraint.constant = self.origBottomConstraintForPwd
                } else if self.currTextField == self.textPwd2 {
                    self.bottomConstraint2.constant = self.origBottomConstraintForPwd2
                }
            }
        })
        
    }

   func textFieldDidBeginEditing(textField: UITextField) {
        currTextField = textField
        if (textField == textPwd || textField == textPwd2) {
            
            needtoAdjustForKeyboard = true
        } else {
            needtoAdjustForKeyboard = false;
        }
        
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
      
    }

}

Be the first to comment

Leave a Reply

Your email address will not be published.


*