Home > AI > IOS > SwiftUI >

@AppStorage

Example 1:

struct ContentView: View {
    // default is watching UserDefaults.standard
    @AppStorage("username") var username: String = "Anonymous"
    @AppStorage("lastname", store: UserDefaults(suiteName: "guest")) var lastname: String = "Anonymous"


    var body: some View {
        VStack {
            Text("Welcome, \(username)!")

            Button("Log in") {
                self.username = "@twostraws"
            }
        }
    }
}

Example 2: pass value through views

struct ContentView: View {
    @AppStorage("text") private var text: String = "Hello"

    var body: some View {
        SecondView(text: $text)
    }
}

struct SecondView: View {
    @Binding var text: String

    var body: some View {
        ThirdView(text: $text)
    }
}

struct ThirdView: View {
    @Binding var text: String

    var body: some View {
        TextEditor(text: $text)
            .padding()
    }
}

Example 3: there is no difference between @AppStorage and UserDefaults.standard.

import SwiftUI
import AVFoundation


struct ContentView: View {
    @EnvironmentObject var home: HomeGlobal
    @AppStorage("test") var test: String = "test"
    

    init() {
        
    }
    var body: some View {
        NavigationView {
            VStack(alignment: .center, spacing: home.defaultPadding) {
                TextField("good", text: $test)
                    .background(Color.blue.opacity(0.2))
                
                Text(test)
                    .background(Color.orange.opacity(0.2))
                
                Text(UserDefaults.standard.value(forKey: "test") as! String)
                
                
                Button {
                    UserDefaults.standard.setValue("newValue", forKey: "test")
                } label: {
                    Text("change")
                }

                NavigationLink(destination: SecondView()) {
                    Text("enter SecondView")
                }
            }
            .padding()
            .frame(width: home.screenWidth/3)
        }
    }
}


struct SecondView: View {
    @AppStorage("test") var test: String = "test"
    
    var body: some View {
        Text(UserDefaults.standard.value(forKey: "test") as! String)
    }
}

Leave a Reply