SwiftUI:切换切换时触发事件

时间:2019-09-23 19:08:37

标签: swift swiftui

当切换状态更改时,我需要发布通知。我找不到为切换指定动作的方法。知道我该怎么做吗?

function duration(t0, t1) {
  let d = (new Date(t1)) - (new Date(t0));
  let weekdays = Math.floor(d / 1000 / 60 / 60 / 24 / 7);
  let years = Math.floor(d / 1000 / 60 / 60 / 24 / 365);
  let months = Math.floor(d / 1000 / 60 / 60 / 24 / 30 - years * 12);
  let weeks = Math.floor(d / 1000 / 60 / 60 / 24 / 7 - years * 52 - months / 7);
  let days = Math.floor(d / 1000 / 60 / 60 / 24 - weekdays * 7);
  let t = {};
  ['years', 'months', 'weeks', 'days', ].forEach(q => {
    if (eval(q) > 0) {
      t[q] = eval(q);
    }
  });
  return t;
}
console.log(duration('1998-02-18', '2019-09-23'));

那又怎样?

1 个答案:

答案 0 :(得分:2)

通常,您不希望视图在更改时负责执行代码,因为您的视图不是真理的源头-它只是对真理源中的更改做出反应。

在这种情况下,您需要的是一个负责保持视图状态的视图模型。更改时,您的视图会做出反应。然后,您可以让视图模型在其属性之一更改时执行代码(例如,使用didSet())。

struct ContentView: View {
    @ObservedObject var model = ListModel()

    var body: some View {
        List {
            ForEach(0..<model.sections.count, id: \.self) { index in
                Section(header: Text(self.model.sections[index].label as String)) {
                    Toggle(isOn: self.$model.sections[index].enabled) {
                        Text("Enabled")
                    }
                }
            }
        }
        .listStyle(GroupedListStyle())
    }
}

class ListModel: ObservableObject {
    @Published var sections: [ListSection] = [
        ListSection(label: "Section One"),
        ListSection(label: "Section Two"),
        ListSection(label: "Section Three")
    ]
}

struct ListSection {
    var label: String
    var enabled: Bool = false {
        didSet {
            // Here's where any code goes that needs to run when a switch is toggled
            print("\(label) is \(enabled ? "enabled" : "disabled")")
        }
    }
}