Tutorial: Moving the Screen When the Keyboard Appears on UITextFields with Swift

When working with UITextFields in iOS applications, it is common to encounter the issue of the keyboard covering the text field, making it difficult for the user to see what they are typing. To solve this problem, you can move the screen up when the keyboard appears, ensuring that the text field remains visible. In this tutorial, we will explore different approaches to achieve this using Swift.

 

Approach 1: Using NotificationCenter

One approach to moving the screen when the keyboard appears is by using the NotificationCenter to observe keyboard-related notifications. Here’s an example implementation:

extension UIViewController {
    func addObserverForNotification(_ notificationName: Notification.Name, actionBlock: @escaping (Notification) -> Void) {
        NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: OperationQueue.main, using: actionBlock)
    }
    
    func removeObserver(_ observer: AnyObject, notificationName: Notification.Name) {
        NotificationCenter.default.removeObserver(observer, name: notificationName, object: nil)
    }
    
    func moveScreenWhenKeyboardAppears() {
        addObserverForNotification(UIResponder.keyboardWillShowNotification) { [weak self] notification in
            guard let self = self else { return }
            
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                // Adjust the view's frame or scroll view's content offset to move the screen up
                // based on the keyboard size
                // Example: self.view.frame.origin.y -= keyboardSize.height
            }
        }
        
        addObserverForNotification(UIResponder.keyboardWillHideNotification) { [weak self] _ in
            guard let self = self else { return }
            
            // Reset the view's frame or scroll view's content offset to its original position
            // Example: self.view.frame.origin.y = 0
        }
    }
    
    func removeKeyboardObserver() {
        removeObserver(self, notificationName: UIResponder.keyboardWillShowNotification)
        removeObserver(self, notificationName: UIResponder.keyboardWillHideNotification)
    }
}

To use this extension, you can call the `moveScreenWhenKeyboardAppears()` function in your view controller’s `viewDidLoad()` method. This will add observers for the keyboard notifications and handle moving the screen when the keyboard appears or hides. Don’t forget to call `removeKeyboardObserver()` in the `viewWillDisappear()` method to remove the observers.

Note: This approach is suitable for UIKit-based applications.

Approach 2: Using SwiftUI

If you are using SwiftUI, you can handle the keyboard appearance and disappearance using the `@ObservedObject` property wrapper and the `onReceive` modifier. Here’s an example implementation:

import SwiftUI
import Combine

class KeyboardResponder: ObservableObject {
    private var cancellables = Set()
    
    @Published var keyboardHeight: CGFloat = 0
    
    init() {
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
            .compactMap { notification in
                notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
            }
            .map { $0.height }
            .assign(to: \.keyboardHeight, on: self)
            .store(in: &cancellables)
        
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
            .map { _ in CGFloat.zero }
            .assign(to: \.keyboardHeight, on: self)
            .store(in: &cancellables)
    }
}

struct ContentView: View {
    @ObservedObject private var keyboardResponder = KeyboardResponder()
    
    var body: some View {
        VStack {
            // Your UI components here
        }
        .padding(.bottom, keyboardResponder.keyboardHeight)
        .animation(.easeOut(duration: 0.25))
    }
}

In this SwiftUI example, we create a `KeyboardResponder` class that observes the keyboard notifications using Combine. The `keyboardHeight` property is updated based on the keyboard’s frame. In the `ContentView`, we use the `@ObservedObject` property wrapper to observe changes to the `keyboardResponder` object. We then adjust the padding of the view’s bottom based on the keyboard height, creating a smooth animation when the keyboard appears or hides.

Note: This approach is suitable for SwiftUI-based applications.

Conclusion

In this tutorial, we explored two approaches to move the screen when the keyboard appears on UITextFields in Swift. The first approach uses NotificationCenter to observe keyboard notifications and adjust the view’s frame or scroll view’s content offset. The second approach is specifically for SwiftUI and uses the `@ObservedObject` property wrapper and Combine to handle keyboard appearance and disappearance.

By implementing these techniques, you can ensure that UITextFields remain visible and provide a better user experience when dealing with keyboard input.

I hope this tutorial helps you in implementing the desired functionality. Let me know if you have any further questions!

Leave a Reply