Coding⏱️ 3 min read📅 2026-06-03

How to Fix: Move view with keyboard using Swift

Adjust the view's frame to move it upwards when the keyboard appears, and then reset it when the keyboard disappears.

Quick Answer: Use Swift's `view.frame.origin.y` property to adjust the view's position.

To resolve the issue of the keyboard covering the text field, you can use Swift's built-in keyboard functionality to manage the view's position.

🛑 Root Causes of the Error

  • The issue arises because the keyboard's appearance triggers a constraint that pushes the view upwards.

🛠️ Step-by-Step Verified Fixes

Method 1: Auto Layout with Keyboard Notification

  1. Step 1: Add the following code to your view controller's viewDidLoad method:
override func viewDidLoad() { super.viewDidLoad() // Notify the keyboard will appear or disappear let notification = NSNotification(name: Notification.Name.keyboardingWillChangeFrame, object: nil, userInfo: [NSKeyboardFrameEndUserInfoKey: true]) self.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: notification.name, object: nil) }

Step 2:

  1. Step 2: Implement the following code in your view controller's keyboardWillChangeFrame method:
func keyboardWillChangeFrame(_ notification: Notification) { var frame = (notification as? NSNotification).userInfo?[NSKeyboardFrameEndUserInfoKey] as? CGRect let originalFrame = self.view.frame // Save the original view frame let newFrame = self.view.frame - frame let constraints = [NSLayoutConstraint.activate([self.textField.heightAnchor.constraint(equalToConstant: newFrame.height)])]

Method 2: Using a Safe Area Layout Guide

  1. Step 1: Add the following code to your view controller's viewDidLoad method:
override func viewDidLoad() { super.viewDidLoad() // Create a safe area layout guide let safeAreaLayoutGuide = self.view.safeAreaLayoutGuide // Pin the text field to the top of the view with the bottom edge constrained to the safe area layout guide NSLayoutConstraint.activate([self.textField.topAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: 0))])}

Step 2:

  1. Step 2: When the keyboard appears, update the constraint to account for its height

💡 Conclusion

By implementing these methods, you can manage the view's position and ensure that the text field remains visible while typing.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions