Published on: May 2, 2020

Keyboard handling using combine

static var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
    let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)
        .map { $0.(userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0 }

    let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification)
        .map { _ in CGFloat(0) }

    return MergeMany(willShow, willHide)
        .eraseToAnyPublisher()
}

Now you can subscribe easily to keyboard height changes.

struct ContentView: View {
    
    @State 
    private var value: String

    var body: some View {
        TextField("Enter the value", text: $value)
            .onReceive(keyboardHeightPublisher) { keyboardHeight in
                if keyboardHeight > 0 {
                    print("Move something up")
                }
            }
    }
}
Tagged with: