0

SwiftUI应用程序中,我需要将焦点设置在 a 上TextField并自动带上键盘,在标准 Swift 中,这将通过以下方式完成:

  field.becomeFirstResponder()

但这似乎并不存在于SwiftUI.

我在这里找到了一份工作。

但是,我的领域使用 :onCommit; 这不在示例代码中。

使用时设置 :onCommit 功能的方法是什么UIViewRepresentable

4

3 回答 3

0

对于 iOS15 有一个由苹果实现的解决方案(正如@AlphaWulf 提到的)

对于 iOS14 在我看来,最好的方法是使用 UIRepresentable 协议实现自己的 TextField 版本。这听起来可能有些困难,但实际上非常简单。

为什么使用视图层次内省在解决方案上实现自己的文本字段会更好?

一个是基于遍历底层视图的解决方案本质上是hacky,即使是小的iOS版本更新也可能会破坏它。

其次,在现实世界的应用程序中,您将希望在文本字段上设置其他内容(例如返回按钮类型和补充视图),但 Apple 没有这样做,您将被迫将 UITextField 包装在任何情况。

https://blog.agitek.io/swiftui-2-first-responder-b6a828243268

在这篇文章中,我有一个详细的解决方案,类似于 Apple 在 SwiftUI 3 中实现的解决方案。

于 2021-07-22T12:57:22.540 回答
0

iOS 15+ 对此有解决方案。

@FocusState 与focused(_:) 修饰符结合可用于控制文本字段的第一响应者状态。

struct ExampleView: View {
    
    @FocusState private var isFocused: Bool
    
    @State private var textInput = ""
    
    var body: some View {
        TextField("Example", text: $textInput)
            .focused($isFocused)
        
        Button("Confirm") {
            if textInput {
                isFocused = true
            }
        }
    }
}
于 2021-06-19T04:38:48.120 回答
-2

在https://github.com/mobilinked/MbSwiftUIFirstResponder有一个满足您需求的开源项目

TextField("Name", text: $name)
    .firstResponder(id: FirstResponders.name, firstResponder: $firstResponder, resignableUserOperations: .all)

TextEditor(text: $notes)
    .firstResponder(id: FirstResponders.notes, firstResponder: $firstResponder, resignableUserOperations: .all)
于 2020-12-04T00:12:28.070 回答