How to get the keyboard height on multiple screens with SwiftUI and move the button

后端 未结 3 575
不知归路
不知归路 2021-02-09 02:22

The following code gets the keyboard height when the keyboard is displayed and moves the button by the keyboard height.

This movement is performed in the same way at the

3条回答
  •  日久生厌
    2021-02-09 03:07

    Using ViewModifier

    You can use ViewModifier of swiftui is much simpler

    import SwiftUI
    import Combine
    
    struct KeyboardAwareModifier: ViewModifier {
        @State private var keyboardHeight: CGFloat = 0
    
        private var keyboardHeightPublisher: AnyPublisher {
            Publishers.Merge(
                NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillShowNotification)
                    .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
                    .map { $0.cgRectValue.height },
                NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillHideNotification)
                    .map { _ in CGFloat(0) }
           ).eraseToAnyPublisher()
        }
    
        func body(content: Content) -> some View {
            content
                .padding(.bottom, keyboardHeight)
                .onReceive(keyboardHeightPublisher) { self.keyboardHeight = $0 }
        }
    }
    
    extension View {
        func KeyboardAwarePadding() -> some View {
            ModifiedContent(content: self, modifier: KeyboardAwareModifier())
        }
    }
    

    And in your view

    struct SomeView: View {
        @State private var someText: String = ""
    
        var body: some View {
            VStack {
                Spacer()
                TextField("some text", text: $someText)
            }.KeyboardAwarePadding()
        }
    }
    

    KeyboardAwarePadding() will automatically add a padding in your view, It's more elegant.

提交回复
热议问题