On the profileView I have button which changes the view to the SettingsView. Which works through a model with I give through an environmentObject. When I'm on the settingsPage(second view) and I change a local variable in that view the profileView goes back to display. So the payload seems to reset when changing a local variable.
ProfileView()
struct ProfileView: View {
@EnvironmentObject var authentication: AuthenticationModel
@ObservedObject var profile: ProfileModel = ProfileModel()
var body: some View {
ZStack {
switch profile.profileView {
case .settings:
SettingsView()
.environmentObject(profile)
.environmentObject(authentication)
.transition(.backslide)
case .profile:
etc...
ProfileModel:
import Foundation
class ProfileModel: ObservableObject {
@Published var profileView: ProfileView = .profile
enum ProfileView {
case profile, settings
}
}
The SettingsView:
When I Click on the button to change DarkMode the payload of the model seems te reset. Resulting in going back to the profileView.
import SwiftUI
//View
struct SettingsView: View {
@EnvironmentObject var authentication: AuthenticationModel
@EnvironmentObject var profile: ProfileModel
//Darkmode
@Environment(\.colorScheme) private var currentColorScheme
@AppStorage("DarkMode") var isDarkMode: Bool = false
var body: some View {
ZStack {
VStack(alignment: .leading) {
//MARK: - Header
HStack {
Button {
profile.profileView = .profile
} label: {
Image(systemName: "chevron.left")
}
Spacer()
} //header
ScrollView {
VStack(alignment: .leading) {
//MARK: - Dark mode
Button {
isDarkMode.toggle() <-- Click results in reset of payload?
} label: {
etc.
I tried it with IF statements, ENUM(switch) one model instead of 2. But it all results in the same.
CodePudding user response:
Change this line in ProfileView
@ObservedObject var profile: ProfileModel = ProfileModel()
To
@StateObject var profile: ProfileModel = ProfileModel()
When an object is created and needs persistence, we need to create it as a StateObject at its point of creation. Everywhere else where it is referred, it has to be either ObservedObject, or EnvironmentObject. Without it being a StateObject somewhere, SwiftUI will not keep its state and will create a new instance every time the view reloads.