Categories
Development

Can’t get Text to update after changing slider

I have a custom embedded View with Text and a Slider that binds to an ObservedObject. I can successfully update the binding with changing the slider but the Text does not update. For some reason, I am really struggling with getting the hang of Property Wrappers and hoping to finally get it to click.

I can easily have the text update when I’m binding the slider value to local state, but no luck with the binding.

class MyItem:ObservableObject, Codable, Identifiable {
    enum CodingKeys: String, CodingKey {
        case calories
    }

    var didChange = PassthroughSubject<Void,Never>()
    var id = UUID()
    var calories:Double = 0 { didSet { update() } 

    func update() {
        didChange.send()
    }
}

struct ContentView:View {
    @ObservedObject var item = MyItem()

    var body:some View {
        MySlider(value: $item.calories)
    }
}

struct MySlider:View {
    @Binding var value:Double

    var body:some View {
        VStack {
            Text("\(value) ")
            Slider(value: $value, in: 0...2000, step:5)
        }
    }
}

Everything works fine, but I can’t get the text in MySlider to update as I mess with the Slider.

Leave a Reply

Your email address will not be published. Required fields are marked *