Home > AI > IOS > SwiftUI >

UserDefaults & SwiftUI

AView.swift

import SwiftUI

struct AView: View {
    var body: some View {
        
        Button(action: {
            UserDefaults.standard.setValue(true, forKey: "userIsLogged")
        }, label: {
            Text("Change User Defaults")
        })
        
    }
}

BView.swift

import SwiftUI

struct BView: View {
    
    @State var userIsLogged: Bool = UserDefaults.standard.bool(forKey: "userIsLogged")
    

    var body: some View {
        Text(String(userIsLogged))
            .background(Color.blue)
            .onAppear{
                // update this value
                userIsLogged = UserDefaults.standard.bool(forKey: "userIsLogged")
            }
    }
}

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack{
                AView()
                
                NavigationLink(
                    destination: BView(),
                    label: {
                        Text("Navigate to BView")
                    })
            }
            
        }
    }
}

This example shows one view (AView.swift) changed the UserDefaults, the situation of updating of another view (BView.swift) of UserDefaults.

  1. the variable userIsLogged in BView get the value of UserDefaults at same time as AView, so without onAppear, you will the BView is not changed, since the variable once get assigned, will not change, same as init.
  2. But onAppear will get called whenever the view is about to present, here we check the newest UserDefaults value and assign that to userIsLogged.

Leave a Reply