How can I run an action when a state changes?

后端 未结 7 2220
醉话见心
醉话见心 2020-12-05 22:25
enum SectionType: String, CaseIterable {
    case top = \"Top\"
    case best = \"Best\"
}

struct ContentView : View {
    @State private var selection: Int = 0

           


        
7条回答
  •  星月不相逢
    2020-12-05 23:22

    Not really answering your question, but here's the right way to set up SegmentedControl (didn't want to post that code as a comment, because it looks ugly). Replace your ForEach version with the following code:

    ForEach(0..

    Tagging views with enumeration cases or even strings makes it behave inadequately – selection doesn't work.

    You might also want to add the following after the SegmentedControl declaration to ensure that selection works:

    Text("Value: \(SectionType.allCases[self.selection].rawValue)")

    Full version of body:

    var body: some View {
        VStack {
            SegmentedControl(selection: self.selection) {
                ForEach(0..

    Regarding your question – I tried adding didSet observer to selection, but it crashes Xcode editor and generates "Segmentation fault: 11" error when trying to build.

提交回复
热议问题