Home > Net >  using variables for a closed range in swift slider
using variables for a closed range in swift slider

Time:01-01

i have the following slider which works as expected, however i want to replace the range 0...100 with min and max variables

Slider(value: $vm.lengthSliderValue,
                   in: 0...100,
                   step: 5,
                   onEditingChanged: { (_) in
                    vm.materialSizeUpdate()
                   },
                   minimumValueLabel: Text(vm.currentValues.wallmin),
                   maximumValueLabel: Text(vm.currentValues.wallmax))
            {
                Text("Select wall thickness")
            }

i've tried the following , but it won't compile. i've tried every variation of the same i can think of but nothing works. how do i replace the range with min and max variables

                let min = Int(vm.currentValues.wallmin)
                let max = Int(vm.currentValues.wallmax)
                
                Slider(value: $vm.lengthSliderValue,
                       in: min ... max,
                       step: 5,
                       onEditingChanged: { (_) in
                        vm.materialSizeUpdate()
                       },
                       minimumValueLabel: Text(vm.currentValues.wallmin),
                       maximumValueLabel: Text(vm.currentValues.wallmax))
                {
                    Text("Select wall thickness")
                }
                Text("\(vm.lengthSliderValue)")

CodePudding user response:

You need to use floating-point types, like

struct TestMinMaxSlider: View {
    @State private var value: Double = 10

    var min: Double = 0
    var max: Double = 100

    var body: some View {
        VStack {
            Text("Value: \(Int(value))")
            Slider(value: $value, in: min...max, step: 5)
        }
    }
}

Tested with Xcode 13.2 / iOS 15.2

demo

  • Related