SwiftUI 可选文本字段 [英] SwiftUI Optional TextField
问题描述
SwiftUI 文本字段可以与可选绑定一起使用吗?目前此代码:
Can SwiftUI Text Fields work with optional Bindings? Currently this code:
struct SOTestView : View {
@State var test: String? = "Test"
var body: some View {
TextField($test)
}
}
产生以下错误:
无法转换类型绑定<"的值String?>' 到预期的参数类型 'Binding<;字符串>'
Cannot convert value of type 'Binding< String?>' to expected argument type 'Binding< String>'
有什么办法可以解决这个问题吗?在数据模型中使用 Optionals 是一种非常常见的模式 - 事实上它是 Core Data 中的默认值,所以 SwiftUI 不支持它们似乎很奇怪
Is there any way around this? Using Optionals in data models is a very common pattern - in fact it's the default in Core Data so it seems strange that SwiftUI wouldn't support them
推荐答案
最终 API 不允许这样做 - 但有一个非常简单且通用的解决方法:
Ultimately the API doesn't allow this - but there is a very simple and versatile workaround:
extension Optional where Wrapped == String {
var _bound: String? {
get {
return self
}
set {
self = newValue
}
}
public var bound: String {
get {
return _bound ?? ""
}
set {
_bound = newValue.isEmpty ? nil : newValue
}
}
}
这允许您在使其与绑定兼容的同时保留可选项:
This allows you to keep the optional while making it compatible with Bindings:
TextField($test.bound)
这篇关于SwiftUI 可选文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!