SwiftUI FocusState 在弹出窗口中不起作用

Ast*_*tro 1 xcode ios swift swiftui

我想在弹出窗口出现时使用键盘激活文本字段,与用户点击相同,但在常规视图中工作时,以下代码在弹出窗口中呈现时不起作用。

有什么解决办法吗?谢谢。

struct ContentView: View {
    
    @State var str = ""
    @State var show = false
    
    @FocusState private var focused: Bool

    var body: some View {
        VStack {
            Text("Popover")
                .onTapGesture {
                    show.toggle()
                }
                .popover(isPresented: $show) {
                    TextField("Popover Textfield", text: $str)
                        .focused($focused)
                        .onAppear {
                            focused = true
                        }
                }
                .frame(width: 100, height: 100)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*nez 5

@FocusState 绑定到根视图,只需像这样分割它:

struct focusText: View {
    @State var str = ""
    @State var show = false
    
    var body: some View {
        VStack {
            Text("Popover")
                .onTapGesture {
                    show.toggle()
                }
                .popover(isPresented: $show) {
                    popView(str: $str)
                }
        }
        .frame(width: 100, height: 100)
    }
}

struct popView: View {
    @Binding var str: String
    @FocusState private var focused: Bool
    
    var body: some View {
        VStack {
            TextField("Popover Textfield", text: $str)
                .focused($focused)
        }
        .onAppear {
            focused = true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,默认情况下模拟器不显示键盘。

在此输入图像描述