swift 切换特定选取器值的视图

xdnvmnnf  于 2022-12-26  发布在  Swift
关注(0)|答案(1)|浏览(95)

当从选取器中选择“自定义”时,我试图显示一个TextField。

struct ContentView: View {
    @State private var color: String = "red" {
        mutating willSet {
            if newValue == "custom" {
                showCutomField = true
            }
            else {
                showCutomField = false
            }
        }
    }
    @State private var customColor: String = ""
    @State private var showCutomField = false
    private var choices = ["red", "green", "blue", "custom"]
    
    var body: some View {
        Form {
            Picker("Color", selection: $color) {
                ForEach(choices, id: \.self) {
                    Text($0)
                }
            }.pickerStyle(.segmented)
            if showCutomField {
                TextField("Color name", text: $customColor)
            }
        }
    }
}

在代码中更改showCustomField的值确实可以显示和隐藏该字段,但是由于某种原因,我无法动态更改该值。

r7xajy2e

r7xajy2e1#

showCustomField可以只是一个计算属性--不需要mutating willSet。它应该是基于color的条件:

struct ContentView: View {
    @State private var color: String = "red"
    @State private var customColor: String = ""
    var showCustomField: Bool {
        color == "custom"
    }
    private var choices = ["red", "green", "blue", "custom"]
    
    var body: some View {
        Form {
            Picker("Color", selection: $color) {
                ForEach(choices, id: \.self) {
                    Text($0)
                }
            }.pickerStyle(.segmented)
            if showCustomField {
                TextField("Color name", text: $customColor)
            }
        }
    }
}

相关问题