ios – Surroundings Variable doesn’t replace robotically on Modifications in SwiftUI?

[ad_1]

Context

I’m storing the present Profile contained in the Surroundings of my App. This works nice, nonetheless, generally SwiftUI doesn’t robotically replace the View when the Worth of this Surroundings Variable adjustments.


Code

struct ProfileEnvironmentKey: EnvironmentKey {
    static var defaultValue: Profile? = nil
}

extension EnvironmentValues {
    public var profile: Profile? {
        get { self[ProfileEnvironmentKey.self] }
        set { self[ProfileEnvironmentKey.self] = newValue }
    }
}

class ProfileViewModel: ObservableObject {
    static let shared = ProfileViewModel()
    
    @Printed non-public(set) var profile: Profile?
    
    func activate(_ profile: Profile) { self.profile = profile }
    func logout() { self.profile = nil }
}

@major struct MedBlockxApp: App {
    @StateObject non-public var profileVM = ProfileViewModel.shared

    var physique: some Scene {
        WindowGroup {
            RootView()
                .atmosphere(.profile, profileVM.profile)
        }
    }
}

struct RootView: View {
    @Surroundings(.profile) non-public var profile: Profile?

    var physique: some View {
        if let safeProfile = profile {
            Textual content(safeProfile.title)
        } else {
            Textual content("Choose a Profile")
        }
    }
}

Query

  • How can or not it’s, that when logging out, the RootView doesn’t replace?

Please word, that in the true App, the LogOut Characteristic is in a distinct Tab of a SwiftUI TabView than the View using the Surroundings. Nevertheless, so far as I do know, the View ought to nonetheless replace.

[ad_2]

Leave a Reply