SwiftUI 状态属性应声明为 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
同样的错误。如何预览私人视图状态?