Binding value for multiple sliders with SwiftUI

Hi,

I have this piece of code to bind the value of one slider in SwiftUI. It works great for one slider, I can set it and keep track of the value in a text field. I am working on an app that has multiple sliders, and I am kind of lost on how to keep track of multiple ones? Do I need to keep this in a class or struct?

Any help or pointing in the right direction is highly appreciated!

Code Block
struct ContentView: View {
    @State private var sliderLevel = 1.0
    var body: some View {
        let intensity = Binding<Double>(
            get: {
                self.sliderLevel
            },
            set: {
                self.sliderLevel = $0
self.applyProcessing()
            }
        )


Answered by BabyJ in 644433022
  1. You can add an @State property for each slider

  2. Create a class conforming to ObservableObject holding all the values

Code Block Swift
class Sliders: ObservableObject {
@Published var slider1 = 1.0
@Published var slider2 = 0.5
@Published var slider3 = 0.0
}
struct ContentView: View {
@ObservedObject var sliders = Sliders()
// or
@State private var slider1 = 1.0
@State private var slider2 = 0.5
@State private var slider3 = 0.0
fileprivate func intensity(for sliderLevel: Binding<Double>) -> Binding<Double> {
Binding<Double>(get: { sliderLevel.wrappedValue }, set: { sliderLevel.wrappedValue = $0.applyProcessing() })
}
var body: some View {...}
}

Accepted Answer
  1. You can add an @State property for each slider

  2. Create a class conforming to ObservableObject holding all the values

Code Block Swift
class Sliders: ObservableObject {
@Published var slider1 = 1.0
@Published var slider2 = 0.5
@Published var slider3 = 0.0
}
struct ContentView: View {
@ObservedObject var sliders = Sliders()
// or
@State private var slider1 = 1.0
@State private var slider2 = 0.5
@State private var slider3 = 0.0
fileprivate func intensity(for sliderLevel: Binding<Double>) -> Binding<Double> {
Binding<Double>(get: { sliderLevel.wrappedValue }, set: { sliderLevel.wrappedValue = $0.applyProcessing() })
}
var body: some View {...}
}

The perfect answer, this helped me a lot. Thank you so much!
Binding value for multiple sliders with SwiftUI
 
 
Q