Reputation: 41738
SwiftUI state properties should be declared as private. This is good for encapsulating their values from containing views, but prevents a preview from setting a non-default state using the default initializer. For example, this doesn't compile:
struct TemperatureView: View {
@State private var isHot = false
var body: some View {
Text(isHot ? "Hot" : "Cold")
}
}
struct TemperatureView_Previews: PreviewProvider {
static var previews: some View {
Group {
TemperatureView(isHot: true)
TemperatureView(isHot: false)
}
}
}
Replacing private
with fileprivate
results in the same error. How can I preview private view state?
Upvotes: 1
Views: 1199
Reputation: 12165
as it is @State
you might want to do:
init() {}
fileprivate init(isHot: Bool) {
self._isHot = State(initialValue: isHot)
}
Upvotes: 5