使用@AppStorage存储非关键数据


7个月前 471次点击 来自 移动端

标签: SwiftUI

iOS14后新增@AppStorage可更方便的读写UserDefaults中的数据:

struct ContentView: View {
    @AppStorage("username") var username: String = "Anonymous"

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

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

如上实例,当Button点击时,同时会执行以下代码:

UserDefaults.standard.set("@twostraws", forKey: "username")

可通过store设置不同的UserDefaults:

@AppStorage("username", store: UserDefaults(suiteName: "group.com.hackingwithswift.unwrap")) var username: String = "Anonymous"

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑