Created
April 21, 2020 03:03
-
-
Save poulter7/48b3952daa1b9438a5f11ad46bc84a10 to your computer and use it in GitHub Desktop.
An example of using UserDefaults
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
// stores the input from the text field | |
@State private var message = "" | |
// stores the saved input | |
// note the this variable is initialized from the UserDefaults | |
@State private var pesistedMessage = UserDefaults.standard.string(forKey: "UserMessage") | |
var body: some View { | |
VStack { | |
// $message means save the result straight into $message, that's temporary | |
TextField("Enter message...", text: $message) | |
Button("Save") { | |
// overwrite the persisted message so it updates the display | |
self.pesistedMessage = self.message | |
// update the persissted message in UserDefaults so it loads by default next time | |
UserDefaults.standard.set( | |
self.pesistedMessage, | |
forKey: "UserMessage" | |
) | |
} | |
// display the persisted message | |
Text("Output: \(pesistedMessage ?? "Default")") | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment