Swift
iOS
Keyboard Handling
TextField
User Interface

Move textfield when keyboard appears swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When developing user interfaces for iOS applications using Swift, a common challenge arises when a text field is obscured by the on-screen keyboard. Ensuring a seamless user experience involves adjusting the UI to move the text field into visibility when the keyboard appears. This article explores how to manage this adjustment effectively, with technical insights and examples.

Understanding Keyboard Notifications

To implement dynamic UI adjustments, respond to keyboard notifications dispatched by NSNotificationCenter. These notifications include:

  • UIKeyboardWillShowNotification: Triggered when the keyboard is about to appear.
  • UIKeyboardWillHideNotification: Triggered when the keyboard is about to disappear.

Subscribing to Keyboard Notifications

Begin by adding observers for these notifications in your view controller's lifecycle methods, such as viewDidLoad():

swift
1override func viewDidLoad() {
2    super.viewDidLoad()
3    
4    NotificationCenter.default.addObserver(self, 
5                                           selector: #selector(keyboardWillShow(_:)), 
6                                           name: UIResponder.keyboardWillShowNotification, 
7                                           object: nil)
8                                           
9    NotificationCenter.default.addObserver(self, 
10                                           selector: #selector(keyboardWillHide(_:)), 
11                                           name: UIResponder.keyboardWillHideNotification, 
12                                           object: nil)
13}

Remember to remove these observers to prevent memory leaks. This is usually done in deinit:

swift
1deinit {
2    NotificationCenter.default.removeObserver(self, 
3                                              name: UIResponder.keyboardWillShowNotification, 
4                                              object: nil)
5    NotificationCenter.default.removeObserver(self, 
6                                              name: UIResponder.keyboardWillHideNotification, 
7                                              object: nil)
8}

Handling Keyboard Appearance

When the keyboard appears, the associated notification carries userInfo dictionary using which you can retrieve the keyboard size. Use this information to adjust the UI accordingly.

Adjusting Layout for Keyboard

Implement the selector methods to handle the keyboard's appearance and disappearance:

swift
1@objc func keyboardWillShow(_ notification: Notification) {
2    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
3        self.view.frame.origin.y = -keyboardSize.height
4    }
5}
6
7@objc func keyboardWillHide(_ notification: Notification) {
8    self.view.frame.origin.y = 0
9}

Understanding Frame Adjustments

The view.frame.origin.y adjustment moves the entire view upwards by the keyboard's height. This ensures that a text field currently in focus will remain visible.

Enhancing the Example with Animation

Adding animations improves the transition for user experience. The UIView class provides simple functions to animate layout changes:

swift
1@objc func keyboardWillShow(_ notification: Notification) {
2    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
3        UIView.animate(withDuration: 0.3, animations: {
4            self.view.frame.origin.y = -keyboardSize.height
5        })
6    }
7}
8
9@objc func keyboardWillHide(_ notification: Notification) {
10    UIView.animate(withDuration: 0.3, animations: {
11        self.view.frame.origin.y = 0
12    })
13}

Considerations for Complex Layouts

For more complex layouts, where only certain UI components need to shift, consider using Auto Layout constraints. Modify constraints directly rather than adjusting frames, offering a more flexible approach that adapts to different device sizes and orientations.

Example with Auto Layout Constraints

Define a constraint to be adjusted when the keyboard appears:

swift
1@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
2
3@objc func keyboardWillShow(_ notification: Notification) {
4    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
5        bottomConstraint.constant = keyboardSize.height
6        UIView.animate(withDuration: 0.3) {
7            self.view.layoutIfNeeded()
8        }
9    }
10}
11
12@objc func keyboardWillHide(_ notification: Notification) {
13    bottomConstraint.constant = 0
14    UIView.animate(withDuration: 0.3) {
15        self.view.layoutIfNeeded()
16    }
17}

Summary

Here is a recap of the key points for managing text field visibility when a keyboard appears:

Key AspectDetails
Keyboard NotificationsUse UIKeyboardWillShowNotification and UIKeyboardWillHideNotification to detect keyboard events.
Notification ObserversAdd observers in viewDidLoad() and remove them in deinit.
Adjusting FramesShift view.frame.origin.y to move entire view when keyboard covers a text field.
Animating TransitionsUse UIView.animate(withDuration:) for smooth transitions.
Auto Layout ConstraintsAdjust layout constraints directly for complex UI structures. Ideal for responsiveness across all screen sizes.

Effectively managing UI adjustments when the keyboard appears results in a more dynamic and intuitive user experience. Adapting these practices will help you maintain visibility of input components and enhance user interactions within your app.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.