访问设置。得分在文本(…)或改变它在按钮()工作得很好,但当我尝试将值写入变量,编译器会报错…任何帮助将是伟大的,谢谢!
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
}
}
不能在VStack
内部赋值。你应该用.onAppear()
。您设置environmentObject
的方式错误
设置你的environmentObject
,你可以初始化你的ContentView。这样的
@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
}
}
}