我在一个应用程序,我希望会有多个视图。我创建了一个类作为ObservableObject,以便能够从多个视图文件访问相同的变量。我想改变一个bool上的文本点击,因为bool改变我想改变的视图。以下是我的文件:
MoodyApp.swift
import SwiftUI
@main
struct MoodyApp: App {
@State var globalVars = vars
var body: some Scene {
WindowGroup {
if(vars.isSettings){
SettingsView()
}
else{
MainView()
}
}
}
}
主视图
import SwiftUI
struct MainView: View {
//colors
let darkGrey : Color = Color(red: 62/255, green: 62/255, blue: 62/255);
let grey : Color = Color(red: 86/255, green: 86/255, blue: 86/255);
let lightGrey : Color = Color(red: 117/255, green: 117/255, blue: 117/255);
let dayGrey : Color = Color(red: 206/255, green: 206/255, blue: 206/255);
let white : Color = Color(red: 242/255, green: 242/255, blue: 242/255);
let years = Callendar();
var body: some View {
VStack(){
VStack{
HStack{
Text("menu")
.foregroundColor(white)
.padding()
Spacer()
Text("settings")
.foregroundColor(white)
.padding()
.onTapGesture(){
//HERE I WANT A BOOL TO CHANGE AND THE APP TO UPDATE THE VIEW
}
}
.ignoresSafeArea()
.frame(height: 0.0)
HStack{
Text("2023")
.font(.system(size:36))
.foregroundColor(white)
}
}.background(darkGrey)
ScrollView(showsIndicators: false){
ForEach(0..<12) { index in
Text(years.month[index])
.font(.system(size:36))
.foregroundColor(white)
.padding(.bottom, -8)
ZStack{
RoundedRectangle(cornerRadius: 45, style: .continuous)
.fill(lightGrey)
.frame(width: 320, height: 320)
ForEach(0..<years.quantity[index], id: .self){ value in
let x = CGFloat(years.positionX[index][value])
let y = CGFloat(years.positionY[index][value])
RoundedRectangle(cornerRadius: 7, style: .continuous)
.fill(dayGrey)
.frame(width: 30, height: 30)
.position(x: x, y: y);
Text(String(value+1))
.position(x: x, y: y)
.foregroundColor(.black);
}
}
}
}
}.background(grey)
.statusBar(hidden: true)
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
这里是globalVars
import Foundation
class GlobalVars: ObservableObject {
@Published var isSettings = false
}
var vars = GlobalVars()
变量正在正确更改,我试图在单击并在控制台中打印后更改它。似乎主应用程序文件不识别的变化??我真的不知道如何解决这个问题,我最近开始在swift工作。如果有任何帮助就太好了。
问题就在这里:
@State var globalVars = vars
是错误的。应该是@StateObject
:
@StateObject var globalVars = vars
,触发它就像:
vars.isSettings = true
备注:
虽然这种方法与全局变量可能工作,它不是一个非常迅速的方法来解决这个问题。您应该在App
结构中初始化GlobalVars
实例,然后将其传递给Views环境。然后把它从环境中拉出来,操纵它。
例如:
struct MoodyApp: App {
@StateObject var globalVars = GlobalVars()
var body: some Scene {
WindowGroup {
if(globalVars.isSettings){
SettingsView()
.environmentObject(globalVars)
}
else{
MainView()
.environmentObject(globalVars)
}
}
}
,然后在视图中:
@EnvironmentObject private var globalVars: GlobalVars
,在onTapGesture
中:
globalVars.isSettings = true