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

发布于 2025-01-11 11:25:13 字数 449 浏览 4 评论 0原文

我在视图中有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过期以后 2025-01-18 11:25:14

只需在 .onAppear 中将 @FocusState 设置为 true 并将其包装在 DispatchQueue.main.asyncAfter 中即可。需要延迟,因为视图必须在 @FocusState 更改之前出现在屏幕上,否则它将无法工作。

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

Simply set your @FocusState to true in .onAppear and wrap it in a DispatchQueue.main.asyncAfter. The delay is needed because the view has to be on screen before the @FocusState is changed or it won't work.

VStack {
  TextField("Name your item...", text: $itemName)
    .focused($keyboardFocused)
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            keyboardFocused = true
        }
    }
  ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文