当 TextField 出现在 SwiftUI 视图上时如何设置 TextField 的焦点

Ber*_*lue 3 swift swiftui

我想要一个文本字段出现在屏幕上时被选中,但我无法让它工作。仅当我点击按钮时,它才在本示例中起作用。

struct ContentView: View {
    @State var text = "Hello World"
    @FocusState var focused: Bool?
    var body: some View {
        VStack {
            TextField("Placeholder", text: $text)
                .focused($focused, equals: true)
                .onAppear {
                    focused = true
                }
            
            Button {
                focused = true
            } label: {
                Text("Select")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

AdR*_*AdR 8

使用asyncAfter()延迟后执行focus = true。尝试这样:

struct ContentView: View {
@State var text = "Hello World"
@FocusState var focused: Bool?
var body: some View {
    VStack {
        TextField("Placeholder", text: $text)
            .focused($focused, equals: true)
            .onAppear {
              DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                self.focused = true
              }
            }
        
        Button {
            focused = true
        } label: {
            Text("Select")
        }
    }
    
}
}
Run Code Online (Sandbox Code Playgroud)