如何关闭键盘并在其后面有一个新视图,同时保持 .toolbar 在 SwiftUI 中可见?

问题描述 投票:0回答:1

我希望能够单击一个按钮来关闭键盘,并用新视图替换键盘空间。 Notion 在他们的应用程序中具有此功能。为了清楚地说明我想要实现的功能,我附上了一张 gif。

swiftui custom-keyboard
1个回答
0
投票

您可以使用

获取键盘的高度
.onReceive(NotificationCenter
    .default
    .publisher(for: UIResponder.keyboardWillShowNotification)
    .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
    .map { $0.cgRectValue.height }, perform: { height in
        self.height = height //Adjust the height based on the keyboard
})

然后通过设置将键盘带入/带出

@FocusState var isFocused: Bool

true
/
false

这是完整的示例。

import SwiftUI

struct KeyboardHeightView: View {
    //Use this to bring/dismiss keyboard
    @FocusState var isFocused: Bool
    @State private var height: CGFloat = 300
    @State private var text: String = "test"
    @ScaledMetric var buttonHeight = 40
    var body: some View {
        VStack{
            TextEditor(text: $text)
                .focused($isFocused)
            //Parent for buttons and actions
            Rectangle()
                .fill(Color.white)
                .border(Color.green)
                .overlay {
                    //Area for buttons and actions
                    VStack {
                        //Space for the buttons
                        HStack{
                            Text("tap to dismiss")
                                .onTapGesture {
                                    isFocused = false //Dismiss Keyboard
                                }
                        }
                        .frame(height: buttonHeight)
                        .frame(maxWidth: .infinity)
                        .border(Color.red)
                        //Space for other actions.
                        Spacer()
                    }
                }
                .frame(height: height + buttonHeight) //Keyboard + the space for the buttons that dismiss keyboard and show actions
        }.ignoresSafeArea(.keyboard)
            .edgesIgnoringSafeArea(.bottom)
            .onReceive(NotificationCenter
                .default
                .publisher(for: UIResponder.keyboardWillShowNotification)
                .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
                .map { $0.cgRectValue.height }, perform: { height in
                    self.height = height //Adjust the height based on the keyboard
                })
            .task {
                isFocused = true //Show keyboard when the View appears
            }
    }
}

#Preview {
    KeyboardHeightView()
}
© www.soinside.com 2019 - 2024. All rights reserved.