Move UITextField when keyboard is presented
It is simple to move the UITextField out of the keyboards way with a few methods using Swift and the UITextFieldDelegate. At the end of this you will be able to recreate the following:
To setup your project to try this out we simply have set the background color to gray, added a UITextField to our view controller and connected it up as a delegate by holding the control key and dragging as follows:
Now with this setup add UITextFieldDelegate to our ViewController class.
class ViewController: UIViewController, UITextFieldDelegate { .... }
Now that you have done this, add the following methods to move the UITextField out of the keyboards way:
// Start Editing The Text Field func textFieldDidBeginEditing(_ textField: UITextField) { moveTextField(textField, moveDistance: -250, up: true) } // Finish Editing The Text Field func textFieldDidEndEditing(_ textField: UITextField) { moveTextField(textField, moveDistance: -250, up: false) } // Hide the keyboard when the return key pressed func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // Move the text field in a pretty animation! func moveTextField(_ textField: UITextField, moveDistance: Int, up: Bool) { let moveDuration = 0.3 let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance) UIView.beginAnimations("animateTextField", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(moveDuration) self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) UIView.commitAnimations() }
In a nutshell, when you edit the text field it moves it up, with the moveTextField. When your finished editing it, the textfield will move back to it’s original place. You can adjust the distance it moves by setting the moveDistance parameter (In our case it is -250).
This code will apply to all text fields on the view, so long as we have connected it up as a delegate.