实例成员不能用于 SwiftUI 预览中的类型

Instance member cannot be used on type in SwiftUI Preview

我的预览出现以下错误:

struct DetailView: View {
    var header: DataProvider.DataHeader

    var body: some View {
        Text("...")
    }
}

struct DetailView_Previews: PreviewProvider {
    var a = DataProvider.DataHeader(title: "a", text: "b")

    static var previews: some View {
        DetailView(header: a)
    }
}

错误是:

Instance member 'a' cannot be used on type 'DetailView_Previews'

为什么会这样?

这是由于static var preview,

所以也可以使用静态

static var a = DataProvider.DataHeader(title: "a", text: "b")

或就地建造

DetailView(header: DataProvider.DataHeader(title: "a", text: "b"))

backup

SwiftUI 预览 -> 您必须在此处使用静态变量:

struct ErrorView_Previews: PreviewProvider {
    @State static var alert = false
    @State static var error = "Please fill all the contents properly"

    static var previews: some View {
        ErrorView(alert: $alert, error: $error)
    }
}