Aim:
I have a model which is an ObservableObject
. It has a Bool
property, I would like to use this Bool
property to initialise a @Binding
variable.
Questions:
- How to convert an
@ObservableObject
to a@Binding
? - Is creating a
@State
the only way to initialise a@Binding
?
Note:
- I do understand I can make use of
@ObservedObject
/@EnvironmentObject
, and I see it's usefulness, but I am not sure a simple button needs to have access to the entire model. - Or is my understanding incorrect ?
Code:
import SwiftUI
import Combine
import SwiftUI
import PlaygroundSupport
class Car : ObservableObject {
@Published var isReadyForSale = true
}
struct SaleButton : View {
@Binding var isOn : Bool
var body: some View {
Button(action: {
self.isOn.toggle()
}) {
Text(isOn ? "On" : "Off")
}
}
}
let car = Car()
//How to convert an ObservableObject to a Binding
//Is creating an ObservedObject or EnvironmentObject the only way to handle a Observable Object ?
let button = SaleButton(isOn: car.isReadyForSale) //Throws a compilation error and rightly so, but how to pass it as a Binding variable ?
PlaygroundPage.current.setLiveView(button)