SwiftUI - 如何在加载视图时自动激活 TextField?

SwiftUI - How to activate TextField automatically when view loads?

我在视图中有一个 TextField,看起来像这样:

@FocusState private var keyboardFocused: Bool

VStack {
  TextField("Name your item...", text: $itemName)
    .focused($keyboardFocused)
  
  ...
}

现在,这一切都嵌入到按下按钮时加载的视图中,如下所示:

Button(action: someAction, label: { ... })
.fullScreenCover(isPresented: $viewIsPresented) {
  ViewWithTextField(...)
}

我想让它在加载此视图时自动激活 TextField/(聚焦?)并弹出键盘。我怎样才能做到这一点?

只需将 @FocusState 设置为 .onAppear 中的 true 并将其包裹在 DispatchQueue.main.asyncAfter 中。延迟是必需的,因为视图必须在 @FocusState 更改之前显示在屏幕上,否则它将不起作用。

VStack {
  TextField("Name your item...", text: $itemName)
    .focused($keyboardFocused)
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            keyboardFocused = true
        }
    }
  ...
}