小编And*_*rew的帖子

SwiftUI:仅当输入不为空时才启用保存按钮

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

// 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 …
Run Code Online (Sandbox Code Playgroud)

swift swiftui combine

5
推荐指数
1
解决办法
1557
查看次数

标签 统计

combine ×1

swift ×1

swiftui ×1