Swift
iOS Development
Keyboard Navigation
User Interface
Mobile Programming

Move view with keyboard using Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

In the world of iOS development, user interface (UI) design plays an essential role in the app's success. One common challenge is handling the keyboard, especially when it covers important UI elements while users are typing. In this article, we'll explore how to effectively move views with the keyboard in Swift, ensuring an optimal user experience.

Setting Up the Project

Before jumping into code, ensure you've set up an Xcode project with a storyboard or using SwiftUI. This guide primarily focuses on UIKit; however, similar principles can be applied to SwiftUI.

Key Concepts

  1. Keyboard Notifications: iOS provides notifications when the keyboard appears or disappears, allowing developers to adjust their UI accordingly.
  2. Constraint Modifications: Change constraints dynamically to move views out of the way.
  3. Animation: Use animations to adjust views smoothly.

Listening to Keyboard Notifications

Xcode offers a set of notifications that tell you when the keyboard appears and disappears:

  • UIKeyboardWillShow
  • UIKeyboardDidShow
  • UIKeyboardWillHide
  • UIKeyboardDidHide

These notifications allow you to adjust your UI dynamically. Here's how you can implement these in your UIViewController.

swift
1class ViewController: UIViewController {
2
3    override func viewDidLoad() {
4        super.viewDidLoad()
5
6        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
7        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
8    }
9
10    deinit {
11        NotificationCenter.default.removeObserver(self)
12    }
13
14    @objc func keyboardWillShow(notification: NSNotification) {
15        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
16            // Implement logic to adjust views
17        }
18    }
19
20    @objc func keyboardWillHide(notification: NSNotification) {
21        // Reset view position
22    }
23}

Adjusting View Positions

To move the view with the keyboard, modify constraints when the keyboard appears and disappears. Suppose we have a UITextField and we wish to move it up when the keyboard appears. Here's an approach:

swift
1var bottomConstraint: NSLayoutConstraint!
2
3override func viewDidLoad() {
4    super.viewDidLoad()
5
6    // Assume textField is initialized and added to the view
7    bottomConstraint = textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20)
8    bottomConstraint.isActive = true
9}
10
11@objc func keyboardWillShow(notification: NSNotification) {
12    if let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
13        let keyboardHeight = keyboardFrame.height
14        bottomConstraint.constant = -keyboardHeight
15
16        UIView.animate(withDuration: 0.3) {
17            self.view.layoutIfNeeded()
18        }
19    }
20}
21
22@objc func keyboardWillHide(notification: NSNotification) {
23    bottomConstraint.constant = -20
24
25    UIView.animate(withDuration: 0.3) {
26            self.view.layoutIfNeeded()
27    }
28}

Using Animation

To make the transition smoother, make use of animations. The UIView.animate block allows the changes to happen over a period (e.g., 0.3 seconds), so the adjustment doesn't happen abruptly.

Best Practices

  • Unsubscribe from Notifications: Always remember to remove the observer when your view controller is deinitialized to prevent memory leaks.
  • Test on Multiple Devices: Ensure you test the implementation on different devices and iOS versions as keyboard handling can vary.
  • Handle Orientation Changes: Consider what happens if the user rotates their device while the keyboard is present. Ensure the views adjust accordingly.

SwiftUI Approach

In SwiftUI, handling the keyboard's presence is slightly different, because you can't directly listen to the same notifications as in UIKit. However, you can use helper libraries like KeyboardObserving which allow you to adjust views in response to the keyboard.

swift
1import SwiftUI
2import Combine
3
4struct ContentView: View {
5    @ObservedObject private var keyboard = KeyboardResponder()
6
7    var body: some View {
8        VStack {
9            Spacer()
10            TextField("Enter text", text: .constant(""))
11                .padding()
12        }
13        .padding(.bottom, keyboard.currentHeight)
14        .animation(.easeOut(duration: 0.16))
15    }
16}

Conclusion

Properly handling the keyboard is crucial for a polished iOS app UI. By subscribing to keyboard notifications and adjusting view constraints with animations, developers can ensure that the user experience remains smooth and intuitive. If you're developing in SwiftUI, leverage available libraries or create a custom solution to handle keyboard interactions efficiently.

Summary Table

AspectUIKitSwiftUI
NotificationsUIKeyboardWillShow UIKeyboardWillHideNot directly available (use Combine)
Modify UIAdjust constraints in handlersUse padding or offset
AnimationUIView.animate block.animation modifier
Memory ManagementRemove observers on deinitHandled automatically

By following these practices, you can optimize your application's UI/UX for a seamless interactive experience on iOS devices.


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.