
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Move Text Field When Keyboard Appears in Swift
In real iOS applications, most of the time you deal with UITextFields for taking various inputs. In order to make the text fields visible while editing, you can manage the constraints by updating them. To manage the constraints, you have to add observers for keyboard showing and hiding.
In this article, we will move the text field when the keyboard appears with the following steps.
Step 1 - Basic setup
In this step, we will do some basic setup by adding a text field to enter the email address. We will add the text field at the bottom of the screen to make it movable when the keyboard appears.
Example
import UIKit class TestController: UIViewController { private lazy var emailTextField: UITextField = { let textField = UITextField() textField.keyboardType = .emailAddress textField.layer.cornerRadius = 8 textField.layer.masksToBounds = true textField.layer.borderWidth = 1.0 textField.layer.borderColor = UIColor(white: 0, alpha: 0.3).cgColor textField.placeholder = "Email Address" textField.textAlignment = .center textField.autocorrectionType = .no textField.delegate = self return textField }() private var textFieldBottomConstraint: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() initialSetup() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // adding notification observers for keyboard show and hide NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // removing all the notification observers NotificationCenter.default.removeObserver(self) } private func initialSetup() { // basic setup view.backgroundColor = .white navigationItem.title = "UITextField" // adding constraints to emailTextField view.addSubview(emailTextField) emailTextField.translatesAutoresizingMaskIntoConstraints = false emailTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true emailTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true emailTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true textFieldBottomConstraint = emailTextField.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100) textFieldBottomConstraint?.isActive = true } @objc private func keyboardWillShow(_ notification: NSNotification) { // write code to complete the implementation } @objc private func keyboardWillHide(_ notification: NSNotification) { // write code to complete the implementation } func updateViewWithKeyboard(notification: NSNotification, viewBottomConstraint: NSLayoutConstraint, keyboardWillShow: Bool) { // write code to complete the implementation } }
Output

In the above code, we did the following things ?
Added an email text field to the view with some constraints.
Declared a variable "textFieldBottomConstraint" to hold a reference to the bottom constraint of the email text field.
Notification observers are now available for the keyboard to reveal and hide. Added these observers in the viewWillAppear method.
Remove the notification observers in viewWillDisappear to avoid unnecessary method calls.
Step 2 - Complete the implementation of the keyboardWillShow and keyboardWillHide methods
During this step, we will complete the code for both methods. Here is the complete code for both methods.
@objc private func keyboardWillShow(_ notification: NSNotification) { // move the text field when the email text field is being edited if emailTextField.isEditing { updateViewWithKeyboard(notification: notification, viewBottomConstraint: self.textFieldBottomConstraint!, keyboardWillShow: true) } } @objc private func keyboardWillHide(_ notification: NSNotification) { // move the field back to the previous position after editing is done updateViewWithKeyboard(notification: notification, viewBottomConstraint: self.textFieldBottomConstraint!, keyboardWillShow: false) }
Step 3 - Complete the implementation of the updateViewWithKeyboard method
We will complete the code for the updateViewWithKeyboard method to support keyboard movement and return to previous positions. Here is the code.
private func updateViewWithKeyboard(notification: NSNotification, viewBottomConstraint: NSLayoutConstraint, keyboardWillShow: Bool) { // getting keyboard size guard let userInfo = notification.userInfo, let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } // getting duration for keyboard animation guard let keyboardDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } // getting keyboard animation's curve guard let keyboardCurve = UIView.AnimationCurve(rawValue: userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int) else { return } // getting keyboard height let keyboardHeight = keyboardSize.cgRectValue.height // setting constant for keyboard show and hide if keyboardWillShow { viewBottomConstraint.constant = -(keyboardHeight + 50) } else { viewBottomConstraint.constant = -100 } // animate the view the same way the keyboard animates let animator = UIViewPropertyAnimator(duration: keyboardDuration, curve: keyboardCurve) { [weak self] in self?.view.layoutIfNeeded() } // perform the animation animator.startAnimation() }
In the above code, we did the following things ?
Get the keyboard size from the user info provided with the notification object.
Get the duration time for keyboard animation from the user info object.
Get the animation type of the keyboard animation from the user info object.
Get the keyboard height and change the constant value of the viewBottomConstraint object.
Animate the view using the UIViewPropertyAnimator class by executing the startAnimation method.
Output

Step 4 - Implement the UITextFieldDelegate method
In this step, we will implement the delegate method to hide the keyboard by clicking the return button. Here is the code.
extension TestController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() } }
Conclusion
To receive keyboard notifications when the keyboard appears and disappears, you can use keyboard notification observers. You can get the keyboard height from the userInfo object that receives in the notification object along with other values. After getting the keyboard height, you can update the constraint value by using the constant property.