SwiftUIでAppStorageを使ってUserDefaultの値を監視する
SwiftUIでAppStorageを使ってUserDefaultの値を監視する方法です。 UserDefaultが変更されると画面が再描画されます。
This file contains hidden or 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 { | |
@AppStorage("FAVORITE_POKEMON_NAME") var favoritePokemonName: String = "" | |
var body: some View { | |
VStack(spacing: 16) { | |
Text("Your favorite pokemon is, \(favoritePokemonName)") | |
Button("Snorlax is my mavorite pokemon.") { | |
favoritePokemonName = "Snorlax" | |
} | |
Button("Snorlax is my mavorite pokemon.") { | |
UserDefaults.standard.set("Slowpoke", forKey: "FAVORITE_POKEMON_NAME") | |
} | |
} | |
} | |
} |