简体   繁体   中英

@EnvironmentObject Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol'

I have an EnvironmentObject that I want to use as a datasource for my button title:

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

在此处输入图像描述

Here is my storage object:

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

Text takes in a String not a Binding<String> . Replace the line you pointed out with the following:

Text(storage.buttonTitle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM