我有两个文本字段和一个保存按钮的视图。如何根据文本字段的内容更改按钮的状态(仅在所有文本字段都不为空的情况下才启用按钮)?这是我当前的代码:
// The variables associated with text fields
@State var name: String = ""
@State var type: String = ""
// I'd like to associate this variable with
// my button's disabled / enabled state,
// but the function responsible for it doesn't accept bindings
@State var canSave: Bool = false
var body: some View {
Form {
TextField("Name", text: $name)
TextField("Type", text: $type)
Button(action: {
// ...
}, label: {
Text("Save")
})
.disabled(!canSave) // no bindings allowed here; what to use indead?
}
}
我有一个想法,应该combineLatest
在最新的Combine框架中使用。但是,无论我尝试谷歌搜索什么,都会带我到RxSwift相关主题,而不是实际的Combine实现。
您似乎对SwiftUI的工作方式有误解。它不依赖于绑定的下坡数据流。它仅取决于状态变量。上坡流程取决于绑定,但是您已经在需要的地方绑定了绑定(除了您的代码错误:您已经将两个文本字段绑定到相同的绑定)。
因此,在这样的简单情况下,您不需要绑定或合并。您具有状态变量,这就是您所需要的:
struct ContentView: View {
@State var name: String = ""
@State var type: String = ""
var body: some View {
Form {
TextField("Name", text: $name)
TextField("Type", text: $type)
Button(action: {
// ...
}, label: {
Text("Save")
}).disabled(name.isEmpty || type.isEmpty)
}
}
}
现在,如果您要验证的文本字段很多,而不仅仅是一两个,那么可以肯定的是,您可以使用发布和订阅将它们组合成一个Bool。但是,让我们首先正确掌握基本原理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句