Reputation: 509
I am trying to update/set my slider value within a button press action.
Button(action: {
if self.questionNum == 1{
print("End")
}else{
self.questionNum -= 1
//This line here is where the value is being set.
self.slider.value = self.model.answers[self.questionNum - 1] as! Double
print(self.model.answers)
print(self.slider.value)
self.questionOpacity = 0
self.model.currentQuestion = self.model.questions[self.questionNum - 1]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
withAnimation(){
self.questionOpacity = 1
}
}
}
}) {
Text("Previous Question")
.font(.system(size: 25))
.fontWeight(.medium)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
}
The slider value actually changes but the dial does not move or update to represent the new value. My Slider value is coming from an Observable object like this one:
class SliderVal: ObservableObject {
var didChange = PassthroughSubject<SliderVal,Never>()
var value = 50.0 {
willSet {
print(self.value)
}
}
The default value of the slider is set to 50 which is the middle, is there any way I can both set and update the slider value to values stored in my array? Outputting the slider value actually gives me the correct result so why is it that the slider dial is not moving/updating?
Thanks
Upvotes: 3
Views: 1943
Reputation: 258345
The pattern you use for ObservableObject
is outdated (it was valid for Beta, now it is not). Instead use default @Published
property wrapper, it will update your view automatically, and provides corresponding bindings if needed.
So here how should your model look...
class SliderVal: ObservableObject {
@Published var value = 50.0
}
and in view (as I understood), it should be declared
@ObservedObject var slider = SliderVal()
Upvotes: 2
Reputation: 8126
example:
struct ContentView: View {
@State var number : Float
var body: some View {
VStack {
Slider(value: $number, in: 1...100)
.padding()
Text("You've selected \(Int(number))")
}.onAppear() {
self.number = 30
}
}
}
Upvotes: 3