我想要一个文本字段出现在屏幕上时被选中,但我无法让它工作。仅当我点击按钮时,它才在本示例中起作用。
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)
使用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)
| 归档时间: |
|
| 查看次数: |
3991 次 |
| 最近记录: |