[英]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!在 Text(...) 中访问 settings.score 或在 Button() 中更改它可以正常工作,但是当我尝试将值写入变量时,编译器会抱怨...任何帮助都会很棒,谢谢!
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
.您不能将值分配给
VStack
内部。 You should use .onAppear()
.您应该使用
.onAppear()
。 And you are using wrong way to set environmentObject
而且您使用错误的方式设置
environmentObject
Set your environmentObject
where you can initialize your ContentView.设置您可以在其中初始化 ContentView 的
environmentObject
。 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.