Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Toggle to disable a Slider in SwiftUI results in styling problems

Tags:

swiftui

Using a Toggle to disable/enable a slider is resulting in the styling being inverted until you interact with the Slider. I'm obviously going about this the wrong way!

struct ContentView: View {
@State var isActive = true
@State var value :Double = 2.0

var body: some View {
    VStack {
        Section(header:
            HStack {
                Toggle(isOn: $isActive)
                    {}.toggleStyle(SwitchToggleStyle(tint: .purple))
            }
        ) {
            HStack {
                Slider(value: $value, in: 0...4, step: 1)
                    .accentColor(isActive ? .purple : .secondary).disabled(!isActive)
                }.pickerStyle(SegmentedPickerStyle())
        }
    }
}
}

Initial state

Disable the toggle - note the Slider style is wrong, but the colour is correct

Enable the toggle again - note the Slider style is now disabled, and the colour (purple which is correct) is in the disabled style

If you interact with the re-enabled slider, the styling fixes itself.

I hope I'm doing something daft here...

like image 281
Ian Avatar asked Oct 16 '25 18:10

Ian


1 Answers

Add .id at the end as show below. This resets slider and it will look as needed. Tested with Xcode 12.1 / iOS 14.1

Slider(value: $value, in: 0...4, step: 1)
    .accentColor(isActive ? .purple : .secondary)
    .disabled(!isActive)
    .id(isActive)           // << this !!
like image 96
Asperi Avatar answered Oct 18 '25 14:10

Asperi