SwiftUI: What is @AppStorage property wrapper

前端 未结 5 2001
攒了一身酷
攒了一身酷 2020-12-19 03:34

I used to save important App data like login credentials into UserDefaults using the following statement:

UserDefaults.standard.set("sample@email.com&quo         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 03:56

    This is a persistent storage provided by SwiftUI. This code will persist the email across app launches.

    struct AppStorageView: View {
        @AppStorage("emailAddress") var emailAddress = "initial@hey.com"
        var body: some View {
            TextField("Email Address", text: $emailAddress)
        }
    }
    

    With pure SwiftUI code, we can now persist such data without using UserDefaults at all.

    But if you do want to access the underlying data, it is no secret that the wrapper is using UserDefaults. For example, you can still update using UserDefaults.standard.set(...), and the benefit is that AppStorage observes the store, and the SwiftUI view will update automatically.

提交回复
热议问题