@EnvironmentObject初始化程序“ init(_ :)”要求“ Binding <String>”符合“ StringProtocol”

时间:2020-04-26 17:34:52

标签: swift swiftui

我有一个EnvironmentObject想要用作按钮标题的数据源:

struct ContentView: View {

    @State var showDetailsView = false
    @EnvironmentObject var storage: Storage

    var body: some View {

        NavigationView {
            ZStack {
                Button(action: {
                    self.doSomethingAsync()
                }) {
                    Text($storage.buttonTitle) // won't compile here

enter image description here

这是我的存储对象:

class Storage: ObservableObject {
    @Published var buttonTitle: String
    @Published var dataObject: DataObject
    init(dataObject: DataObject = DataObject(name: "Test")) {
        self.dataObject = dataObject
        buttonTitle = "Try"
    }
}

1 个答案:

答案 0 :(得分:1)

Text接受String而不是Binding<String>。用以下内容替换您指出的行:

Text(storage.buttonTitle)