【问题标题】:SwiftUI: Enable save button only when the inputs are not emptySwiftUI:仅当输入不为空时才启用保存按钮
【发布时间】:2019-11-19 20:20:08
【问题描述】:

我有一个包含两个文本字段和一个保存按钮的视图。如何根据文本字段的内容更改按钮的状态(我只想在所有文本字段都不为空的情况下启用按钮)?这是我当前的代码:

// 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?
    }
}

我有一个想法,我应该使用最新的 Combine 框架中的 combineLatest。但是无论我尝试用谷歌搜索什么,都会将我引向与 RxSwift 相关的主题,而不是实际的 Combine 实现。

【问题讨论】:

    标签: swift swiftui combine


    【解决方案1】:

    您似乎对 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)
            }
        }
    }
    

    现在,如果您有许多文本字段要验证,而不仅仅是一两个,那么当然,您可以使用发布和订阅将它们组合成一个布尔值。但让我们先搞清楚基本原则。

    【讨论】:

      【解决方案2】:

      您可以在视图末尾添加一些代码。这只是为了简单的逻辑,否则,您可能需要创建一些模型。

       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?
      }.onReceive(Publishers.CombineLatest(Just( name.isEmpty), Just(type.isEmpty))){
          self.canSave = !($0.0 || $0.1)
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-02
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 2017-11-06
        • 2018-10-10
        相关资源
        最近更新 更多