SwiftUIでAppDelegateを使用する
SwiftUIでAppDelegateを使用する方法です。アプリ終了時にUserDefaultsに値を保存しています。

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 { | |
@State var pokemon = "" | |
var body: some View { | |
VStack { | |
Text("Pokemon Name is \(pokemon)") | |
Button { | |
UserDefaults().setValue("Pikachu", forKey: "POKEMON") | |
getPokemon() | |
} label: { | |
Text("Set Pikachu") | |
} | |
Button { | |
UserDefaults().setValue("Ditto", forKey: "POKEMON") | |
getPokemon() | |
} label: { | |
Text("Set Ditto") | |
} | |
Button { | |
UserDefaults().setValue("Slowpoke", forKey: "POKEMON") | |
getPokemon() | |
} label: { | |
Text("Set Slowpoke") | |
} | |
} | |
.onAppear { | |
getPokemon() | |
} | |
} | |
func getPokemon() { | |
if let pokemon = UserDefaults().value(forKey: "POKEMON") as? String { | |
self.pokemon = pokemon | |
} | |
} | |
} |