Keyboard offset no longer functions in SwiftUI 2

Published

So I have an ObservableObject that sets a published variable ‘currentHeight’ to the height of the keyboard:

import Foundation
import SwiftUI

class KeyboardResponder: ObservableObject {

@Published var currentHeight: CGFloat = 0

var _center: NotificationCenter

init(center: NotificationCenter = .default) {
    _center = center
    _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyBoardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        withAnimation {
           currentHeight = keyboardSize.height
        }
    }
    print("the KEYBOARD HEIGHT IS (self.currentHeight)")
}

@objc func keyBoardWillHide(notification: Notification) {
    withAnimation {
       currentHeight = 0
    }
    print("the KEYBOARD HEIGHT IS (self.currentHeight)")
}
}

In my other views, I create an ObservedObject keyboardResponder and then inside the body of the view, I’ll have for example some view where I set the vertical offset:

struct ViewName: View {
    @ObservedObject var keyboardResponder = KeyboardResponder()
    var body: some View {
        VStack {
            Text("this should be offset")
            .offset(y: -keyboardResponder.currentHeight)
        }
    }
}

Before Xcode 12/SwiftUI 2 dropped, this worked like a charm but I think they changed something with how views refresh–anyone know what they changed and if there is a solution to my issue here?

Source: Swift Questions

Published
Categorised as keyboard, offset, swift, swiftui, xcode Tagged , , , ,

Answers

As of the latest Swift, Xcode 12 and iOS14, I noticed that it is standard build in, when the textfield is not visible when typing. The screen is being risen with the keyboard height and shows the original field. Try this out with a scrollable view and 20 textfields for example.
Maybe you can get rid of your observableheight and do it without hard coding it.

enter image description here


Christop Pollich I

Leave a Reply

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

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq