swift 如何使键盘永久显示在屏幕上

ac1kyiln  于 2023-02-28  发布在  Swift
关注(0)|答案(1)|浏览(162)

我的SwiftUI应用程序中有以下组件:

struct ContentView: View {
    var search = Search()
   
    @FocusState private var fieldIsFocused: Bool
    
    @State private var word: String = ""
    var body: some View {
            VStack(alignment: .leading) {
                Text(word).font(.title2)
                Spacer()
                HStack{
                    Image(systemName: "magnifyingglass")
                    TextField(
                        "Search ...",
                        text: $word
                    )
                        .autocorrectionDisabled()
                        .autocapitalization(.none)
                        .textFieldStyle(.roundedBorder)
                        .onSubmit {
                            fieldIsFocused = true
                        }
                        .focused($fieldIsFocused)
                        .onAppear {
                            fieldIsFocused = true
                        }
                }
                .padding()

                        
            }
}

我想让键盘一直显示在屏幕上。也就是说,文本字段总是被聚焦。我可以通过在字段出现和提交时将fieldIsFocused设置为true来实现这一点,但这会导致键盘开始向下滑动,然后又弹回来的不稳定动画。我正在寻找一个更干净的解决方案来一直保持键盘。

roejwanj

roejwanj1#

这是我只用SwiftUI想到的最好的

struct ContentView: View {
    @State var word = ""
    @StateObject var textHolder = TextHolder()
    @FocusState var fieldIsFocused: Bool

    var body: some View {
        VStack(alignment: .leading) {
            Text(word).font(.title2)
            Spacer()
            HStack {
                Image(systemName: "magnifyingglass")
                TextField("Search ...", text: $textHolder.text)
                    .autocorrectionDisabled()
                    .autocapitalization(.none)
                    .textFieldStyle(.roundedBorder)
                    .keyboardType(.twitter)
                    .focused($fieldIsFocused)
            }
            .padding()
        }
        .onAppear {
            fieldIsFocused = true
            textHolder.onSubmit = { word = textHolder.text }
        }
    }
    
    final class TextHolder: ObservableObject {
        @Published private var _text = ""
        
        var text: String {
            get { _text }
            set {
                _text = String(newValue.filter { $0 != "#" })
                if newValue.contains(where: { $0 == "#" }) {
                    onSubmit()
                }
            }
        }
        var onSubmit = {}
    }
}

根据苹果提供的功能,键盘不会在回车键时隐藏的唯一情况是keyboardType ==. twitter。但是现在我们需要避免标签,并在有标签时执行提交。这就是TextHolder所做的。请记住,每当用户键入“#”时,它都会触发提交

相关问题