简体   繁体   中英

SwiftUI: Fire an event when a toggle is switched

I need to post notification when the state of a toggle changes. I couldn't find a way to specify an action for a toggle. Any idea how I can do that?

var body: some View {
    List {
        ForEach(items.indices) { index in
            Section(header: Text(self.items[index].label)) {
                Toggle(isOn: self.$items[index].isOn) {
                    Text("Enabled")
                }
            }
        }
    }
    .listStyle(GroupedListStyle())
}

But then what??

In general, you don't want your view to be in charge of executing code when it changes, because your view is not the source of truth - it merely responds to changes in your source of truth.

In this case, what you want is a view model that is in charge of keeping your view's state. When it changes, your view reacts. Then you can have that view model execute code when one of its properties changes (using didSet(), for example).

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")")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM