问题描述
在SwiftUI
应用中,我需要将焦点放在TextField
上并自动带动键盘,在标准Swift中,这可以通过以下方式完成:
field.becomeFirstResponder()
但这SwiftUI
中似乎不存在。
但是,我的领域使用:onCommit;。不在示例代码中。
使用UIViewRepresentable
时,如何设置:onCommit功能?
解决方法
有一个满足您需求的开源项目,位于https://github.com/mobilinked/MbSwiftUIFirstResponder
TextField("Name",text: $name)
.firstResponder(id: FirstResponders.name,firstResponder: $firstResponder,resignableUserOperations: .all)
TextEditor(text: $notes)
.firstResponder(id: FirstResponders.notes,resignableUserOperations: .all)
,
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
}
}
}
}
,
对于 iOS15 有一个由苹果实现的解决方案(如@AlphaWulf 所述)
对于 iOS14 在我看来,最好的方法是使用 UIRepresentable 协议实现您自己的 TextField 版本。这听起来可能有些困难,但实际上很简单。
为什么最好使用视图层次结构自省在解决方案上实现您自己的文本字段?
一个是基于遍历底层视图的解决方案本质上是hacky,即使是较小的iOS版本更新也可能会破坏它。
其次,在现实世界的应用程序中,您将需要在文本字段上设置其他内容(例如返回按钮类型和补充视图),但 Apple 没有这样做,您将被迫换行无论如何都是 UITextField。
https://blog.agitek.io/swiftui-2-first-responder-b6a828243268
在这篇文章中,我有一个详细的解决方案,类似于 Apple 在 SwiftUI 3 中实施的解决方案。