简体   繁体   中英

Access a @Published variable does not compile; “cannot conform to 'View'; only struct/enum/class types can conform to protocols”

Accessing settings.score in Text(...) or changing it in Button() works fine, but when I try to write the value into a variable, the compiler complains... Any help would be great, thank you!

import SwiftUI

struct ContentView: View
{
  @EnvironmentObject var settings: UserSettings // settings are initialized in AppDelegate
  @State var myscore: Int = 0

  var body: some View
  {
    NavigationView
    {
      VStack
      {
        myscore = settings.score // COMPILER FAIL: Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
        Text("\(settings.score)")   // here score shows up correct!
          .padding()

        Button("Increase Score")
        {
          settings.score += 1 // this also works
        }
        .padding()

        NavigationLink(destination: DetailView())
        {
          Text("Show Detail View")
        }
      }
    }
    .environmentObject(self.settings)}
}
  
 class UserSettings: ObservableObject
{
  @Published var score: Int = 0
  
  init(_ value: Int)
  {
    self.score = value
  }
}

You can not assign value to inside the VStack . You should use .onAppear() . And you are using wrong way to set environmentObject

Set your environmentObject where you can initialize your ContentView. like this

@main
struct ContentViewApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(UserSettings(15))
        }
    }
}
struct ContentView: View {
    @EnvironmentObject var settings: UserSettings // settings are initialized in AppDelegate
    @State var myscore: Int = 0

    var body: some View {
        NavigationView {
            VStack {
                Text("\(settings.score)")   // here score shows up correct!
                    .padding()
                
                Button("Increase Score") {
                    settings.score += 1 // this also works
                }
                .padding()
                
                NavigationLink(destination: DetailView()) {
                    Text("Show Detail View")
                }
            }
        }
        .onAppear {
            myscore = settings.score //<=== Here
        }
    }
}

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