更改状态变量/切换分段控制时调用函数

时间:2020-04-03 14:04:49

标签: ios swift xcode swiftui swift5

我正在尝试找出如何调用功能来更新Firebase数据库在切换分段控件时。有什么想法吗?尝试过 didSet(),但似乎不起作用。

变量

@State var exteriorIndex = 1

分段控制:

Picker("Numbers", selection: $exteriorIndex) {
                ForEach(0 ..< exteriorOptions.count) { index in
                    Text(self.exteriorOptions[index]).tag(index)
                }
            }
            .pickerStyle(SegmentedPickerStyle())
            .frame(width: 950/2, height: 78/2)

DataUpdate() 函数(需要调用)

func dataUpdate() {
    print("DataUpdate Running..")

    var exterior = false
    if exteriorIndex == 1 {
        exterior = true
    }

    else {
        exterior = false
    }

    let db = Firestore.firestore()

    db.collection("settings").document("LI").setData([
        "exterior": exterior
    ]) { err in
        if let err = err {
            print("Error writing document: \(err)")
        } else {
            print("Document successfully written!")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用此

Picker("Numbers", selection: Binding<Int>(
    get: { self.exteriorIndex },
    set: {
            self.exteriorIndex = $0
            self.dataUpdate()
    }) {
    ...