如何使用UserDefaults SwiftUI?

时间:2019-12-02 13:08:13

标签: swift swiftui userdefaults

我正在尝试创建一个text field,其中的文本变为varuser default,这些文本将一直显示。

我试图使它等于在本节中设置的变量。 但是我真的不知道我在做什么。

@State private var Name = UserDefaults.standard.string(forKey: "name")

Section{
  TextField("Name", text: $Name)
  UserDefaults.standard.set($Name, forKey: "name")
}

1 个答案:

答案 0 :(得分:0)

结构默认值{

static let (nameKey, addressKey) = ("name", "address")
static let userSessionKey = "com.save.usersession"
private static let userDefault = UserDefaults.standard

/**
   - Description - It's using for the passing and fetching
                user values from the UserDefaults.
 */
struct UserDetails {
    let name: String
    let address: String

    init(_ json: [String: String]) {
        self.name = json[nameKey] ?? ""
        self.address = json[addressKey] ?? ""
    }
}

/**
 - Description - Saving user details
 - Inputs - name `String` & address `String`
 */
static func save(_ name: String, address: String){
    userDefault.set([nameKey: name, addressKey: address], 
                    forKey: userSessionKey)
}

/**
 - Description - Fetching Values via Model `UserDetails` you can use it based on your uses.
 - Output - `UserDetails` model
 */
static func getNameAndAddress()-> UserDetails {
    return UserDetails((userDefault.value(forKey: userSessionKey) as? [String: String]) ?? [:])
}

/**
    - Description - Clearing user details for the user key `com.save.usersession`
 */
static func clearUserData(){
    userDefault.removeObject(forKey: userSessionKey)
}

}