我对 SwiftUI 相当陌生,我正在尝试构建一个小游戏来习惯语法,但我遇到了一个问题,我创建了一个类并在 @main 结构中创建了 3 个实例,但是当我尝试在我的视图中使用它们时,它们全部变成第一个实例
班级:
import Foundation
class WorkSpace: ObservableObject {
var title: String
var income: Int
init(title: String, income: Int) {
self.title = title
self.income = income
}
}
@主结构:
import SwiftUI
@main
struct LifeSimulationApp: App {
@StateObject var doctor = WorkSpace(title: "Doctor", income: 60000)
@StateObject var lawyer = WorkSpace(title: "Lawyer", income: 50000)
@StateObject var carseller = WorkSpace(title: "Car Seller", income: 30000)
@StateObject var player = MainPlayer()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(doctor)
.environmentObject(lawyer)
.environmentObject(carseller)
.environmentObject(player)
}
}
}
查看:
import SwiftUI
struct OccupationView: View {
@EnvironmentObject var doctor: WorkSpace
@EnvironmentObject var lawyer: WorkSpace
@EnvironmentObject var carseller: WorkSpace
@EnvironmentObject var player: MainPlayer
var body: some View {
NavigationView {
Form {
HStack {
Image(systemName: "text.book.closed.fill")
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.blue)
.padding()
Spacer()
Text(player.occupation)
.font(.title)
.padding()
Spacer()
}
Section {
Toggle("\(doctor.title) (\(doctor.income)€)", isOn: $player.isDoctorOn)
Toggle("\(lawyer.title) (\(lawyer.income)€)", isOn: $player.isLawyerOn)
Toggle("\(carseller.title) (\(carseller.income)€)", isOn: $player.isCarsellerOn)
}
}
.navigationTitle(player.name)
}
}
}
struct OccupationView_Previews: PreviewProvider {
static var previews: some View {
OccupationView()
.environmentObject(MainPlayer())
.environmentObject(WorkSpace(title: "Doctor", income: 60000))
.environmentObject(WorkSpace(title: "Lawyer", income: 50000))
.environmentObject(WorkSpace(title: "Car Seller", income: 30000))
}
}
预览: 在此输入图片描述
这是因为每种类型只能有一个
@EnvironmentObject
,因为编译器只检查类型。实际上,您可以根据需要命名环境变量,只要类型正确并且它会识别它即可。您有几个选择,最简单的就是创建一个包含您需要的所有 WorkSpace 对象的 ObservableObject。
根据您的用例,您还可以扩展环境值以包含医生、律师和您需要的任何其他内容。
或者您可以只在 inits 中传递 StateObjects。