import SwiftUI
struct SettingsView: View {
@State private var name: String = ""
@State private var notificationsEnabled: Bool = false
var body: some View {
NavigationView {
Form {
Section(header: Text("User Info")) {
TextField("Enter your name", text: $name)
}
Section(header: Text("Preferences")) {
Toggle(isOn: $notificationsEnabled) {
Text("Enable Notifications")
}
}
Button("Save") {
UserDefaults.standard.set(name, forKey: "userName")
UserDefaults.standard.set(notificationsEnabled, forKey: "notificationsEnabled")
}
}
.navigationTitle("Settings")
.onAppear {
if let savedName = UserDefaults.standard.string(forKey: "userName") {
name = savedName
}
notificationsEnabled = UserDefaults.standard.bool(forKey: "notificationsEnabled")
}
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}This solution uses UserDefaults.standard to save and load simple values.
When the Save button is tapped, it saves the current name string and notificationsEnabled boolean to UserDefaults with keys "userName" and "notificationsEnabled".
When the view appears, it reads these values back from UserDefaults. If a saved name exists, it updates the name state. It also reads the boolean for notifications, defaulting to false if not set.
This way, the user's settings persist between app launches, and the UI always shows the saved values.