How to set multiple values in sliders?

Viewed 30

I’m trying to create view with multiple sliders. The question is how can I assign values for each of sliders in this case? Now all sliders move simultaneously. I tried to add Binding value property in Character structure and pass them in SliderView but in this case slider doesn’t move

struct SliderView: View {

private var label: String
private var min: Double
private var max: Double

@Binding private var value: Double

init(label: String,
     value: Binding<Double>,
     min: Double,
     max: Double) {

    self.label = label
    _value = value
    self.min = min
    self.max = max
}

var body: some View {
    VStack(alignment: .leading, spacing: 17) {
        HStack {
            Text(label)
            Spacer()
            Text("\(value, specifier: "%.2f")")
        }
        Slider(value: $value,
               in: min...max)
    }
    .padding()
}
}

struct PersonalityView: View {
    
    @State var value: Double
    
    var person: [Character] = [.init(quality: "Angry", min: 1.0, max: 100.0),
                                .init(quality: "Kind", min: 1.0, max: 100.0),
                                .init(quality: "Wise", min: 1.0, max: 100.0),
                                .init(quality: "Greedy", min: 1.0, max: 100.0)]
    
    var body: some View {
        VStack {
            ForEach(person, id: \.self) { person in
                SliderView(label: person.quality,
                            value: $value,
                            min: person.min,
                            max: person.max)
            }
        }
    }
}

struct PersonalityView_Previews: PreviewProvider {
    static var previews: some View {
        PersonalityView(value: 0.5)
    }
}
1 Answers

You need to add the value to the Character struct:

struct PersonalityView: View {
    
    //@State var value: Double not needed anymore
    
    @State var people: [Character] = [.init(quality: "Angry", min: 1.0, max: 100.0, value: 10.0),
                                .init(quality: "Kind", min: 1.0, max: 100.0, value: 30.0),
                                .init(quality: "Wise", min: 1.0, max: 100.0, value: 20.0),
                                .init(quality: "Greedy", min: 1.0, max: 100.0, value: 16.0)]
    
    var body: some View {
        VStack {
            ForEach($people, id: \.self) { person in
                SliderView(label: person.quality.wrappedValue,
                       value: person.value,
                       min: person.min.wrappedValue,
                       max: person.max.wrappedValue)
            }
        }
    }
}
Related