0

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

1 Answer 1

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()
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.