otterpops
otterpops

Reputation: 11

How to set @State variable in If / Else statement

I have this simple code that uses a toggle to show/hide a slider. When the slider is visible, the user can change the value between 0...5. I want it to reset the @State variable to 0 if someone chooses to switch the toggle to off. When I add anything to the Else I get "Type '()' cannot conform to 'View'"

Any help is much appreciated.

struct Test: View {
    
    @State var sliderValue = 0.0
    @State var toggleIsOn = false
    
    var body: some View {
        VStack {
            Toggle(isOn: $toggleIsOn) {
                HStack {
                    Text("Slider Value:")
                    Text("\(sliderValue)")
                }
            }
            if toggleIsOn {
                Text("\(sliderValue)")
                Slider(value: $sliderValue, in: 0...5)
            } else {
                sliderValue = 0.0
            }
            Spacer()
        }
    }
}

Upvotes: 0

Views: 116

Answers (1)

you could try the following approach, or some variation of this, using the .onChange(...):

struct Test: View {
    @State var sliderValue = 0.0
    @State var toggleIsOn = false
    
    var body: some View {
        VStack {
            Toggle(isOn: $toggleIsOn) {
                HStack {
                    Text("Slider Value:")
                    Text("\(sliderValue)")
                }
            }
            .onChange(of: toggleIsOn) { value in
                if !value { sliderValue = 0.0 }
            }
            if toggleIsOn {
                Text("\(sliderValue)")
                Slider(value: $sliderValue, in: 0...5)
            }
            Spacer()
        }
    }
}

Upvotes: 1

Related Questions