How can I run an action when a state changes?

后端 未结 7 2184
醉话见心
醉话见心 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..<SectionType.allCases.count) { index in 
        Text(SectionType.allCases[index].rawValue).tag(index)
    }
    

    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..<SectionType.allCases.count) { index in
                    Text(SectionType.allCases[index].rawValue).tag(index)
                    }
                }
    
            Text("Value: \(SectionType.allCases[self.selection].rawValue)")
        }
    }
    

    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.

    0 讨论(0)
提交回复
热议问题