How to prevent the keyboard from hiding your SwiftUI view

Share on facebook
Share on twitter
Share on pinterest

To deliver a good user experience, you have to make sure that the user can see what he is typing. Therefore, it’s crucial to prevent the toggled keyboard from hiding your view’s content.


We can achieve this by offsetting the whole SwiftUI view by the height of the toggled keyboard. We could use a fixed value for this, but keep in mind that for example, the keyboard height of an iPhone 8 differs tremendously from the height of an iPad Pro. So how can we access the keyboard’s heigh and use it for offsetting our SwiftUI view? Well, here you go:

If you want to learn how to create a login screen like the one you see in the preview video, take a look at this tutorial or download the finished project.

Step 1: Create a new Swift file called KeyboardResponder and import the SwiftUI framework. Then create a class that adopts the ObservableObject protocol. Our KeyboardResponder needs to be observable so we can update the observing views when the keyboard got toggled.⠀

import Foundation
import SwiftUI

class KeyboardResponder: ObservableObject {

}

Step 2: For keeping track of the keyboard’s current height, we declare a @Published property and assign it to 0 by default. 0 represents that the keyboard is not opened. Whenever the keyboard shows up we will update the published property with the actual keyboard height which will cause the observing views to update themselves.⠀

class KeyboardResponder: ObservableObject {

    @Published var currentHeight: CGFloat = 0

}

Step 3: To achieve this, we can use the system’s built-in keyboardWillShowNotification and keyboardWillHideNotifaction. To handle these notifications, we need to initialise a NotificationCenter first.⠀

class KeyboardResponder: ObservableObject {
//...
    
var _center: NotificationCenter

    init(center: NotificationCenter = .default) {
        _center = center
    }
}

Step 4: Then we tell our notification center to listen to the system’s keyboardWillHide/Show notifications. Whenever the keyboards gets shown/hidden now, the Notification Center will execute the function targeted by the specific selector.⠀

init(center: NotificationCenter = .default) {
        _center = center
    //4. Tell the notification center to listen to the system keyboardWillShow and keyboardWillHide notification
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

Step 5: Until now, we didn’t implement the functions called by the selectors. Let’s change this by adding these to our KeyboardResponder. Whenever the keyboard gets toggled now, our Notification Center notices and calls the corresponding function. Inside this function, we update the currentHeight property by referring to the keyboard size. As said this will cause all observing views to update themselves.

@objc func keyBoardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            withAnimation {
               currentHeight = keyboardSize.height
            }
        }
    }
@objc func keyBoardWillHide(notification: Notification) {
        withAnimation {
           currentHeight = 0
        }
    }

Step 6: To observe the KeyboardResponder we have to initialise it inside our SwiftUI view as an @ObservedObject.

struct ContentView: View {
//...
    
@ObservedObject var keyboardResponder = KeyboardResponder()
var body: some View {
//...
    }
}

Step 7: Finally we tell our view to have the same offset as the keyboard is high by referring to the currentHeight variable of the observed KeyboardResponder.

var body: some View {
        NavigationView {
//...
        }
            .offset(y: -keyboardResponder.currentHeight*0.9)
    }

If you now run your app and open the keyboard, for example by tapping on a text field, the whole content moves up so we’re able to read what we’re writing.

That’s it! I hope you enjoyed this brief SwiftUI tutorial! 🍀

You can download the full source code here.

By the way, did you already download our FREE SwiftUI Basics eBook? Make sure you click the link in the bio to check it out 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount

small_c_popup.png

Are you ready for a new era of iOS development?

Start learning swiftUI today - download our free e-book