SwiftUI - 如何在视图加载时自动激活 TextField?
我在视图中有一个 TextField,看起来像这样:
@FocusState private var keyboardFocused: Bool
VStack {
TextField("Name your item...", text: $itemName)
.focused($keyboardFocused)
...
}
现在,这一切都嵌入在按下按钮时加载的视图中,如下所示:
Button(action: someAction, label: { ... })
.fullScreenCover(isPresented: $viewIsPresented) {
ViewWithTextField(...)
}
我想这样做,以便在加载此视图时,自动激活 TextField /(聚焦?)然后键盘弹出。我怎样才能做到这一点?
I have a TextField in a view that looks something like this:
@FocusState private var keyboardFocused: Bool
VStack {
TextField("Name your item...", text: $itemName)
.focused($keyboardFocused)
...
}
Now, this is all embedded in a view that loads when a button is pressed, like this:
Button(action: someAction, label: { ... })
.fullScreenCover(isPresented: $viewIsPresented) {
ViewWithTextField(...)
}
I want to make it so that when this view loads, the TextField is automatically activated/(focused?) and the keyboard pops up. How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在
.onAppear
中将@FocusState
设置为true
并将其包装在DispatchQueue.main.asyncAfter
中即可。需要延迟,因为视图必须在@FocusState
更改之前出现在屏幕上,否则它将无法工作。Simply set your
@FocusState
totrue
in.onAppear
and wrap it in aDispatchQueue.main.asyncAfter
. The delay is needed because the view has to be on screen before the@FocusState
is changed or it won't work.