预览 SwiftUI private non-default @State

Preview SwiftUI private non-default @State

SwiftUI 状态属性 should be declared as private。这有利于从包含视图中封装它们的值,但会阻止预览使用默认初始化程序设置非默认状态。例如,这不会编译:

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)
        }
    }
}

private 替换为 fileprivate 会导致相同的错误。如何预览私有视图状态?

因为它是 @State 你可能想做:

init() {}

fileprivate init(isHot: Bool) {
    self._isHot = State(initialValue: isHot)
}