考虑以表格形式呈现的以下
PreferencesView
:
struct PreferencesView: View {
@Environment(\.dismiss) private var dismiss
@AppStorage("setting1") var setting1: Bool = true
@AppStorage("setting2") var setting2: Bool = false
@AppStorage("setting3") var setting3: Bool = false
// many more
var body: some View {
NavigationView {
Form {
Toggle("Setting 1", isOn: $setting1)
Toggle("Setting 2", isOn: $setting2)
Toggle("Setting 3", isOn: $setting3)
}
.navigationTitle("Preferences")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
reset()
dismiss()
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
dismiss()
}
}
}
}
}
private func reset() {
// what do I put here?
}
}
如果用户点击取消,我希望将设置值设置回打开工作表时的值。我可以添加单独的
initialSetting1
等属性,然后在 reset
函数中添加 setting1 = initialSetting1
。但设置很多就变得乏味了。
还有别的办法吗?
onAppear
@State
绑定到切换开关@State
保存到设置。像这样:
struct PreferencesView: View {
@Environment(\.dismiss) private var dismiss
@AppStorage("setting1") var setting1: Bool = true
@AppStorage("setting2") var setting2: Bool = false
@AppStorage("setting3") var setting3: Bool = false
// Initial value doesn't matter, will be overwritten
@State var currentSetting1: Bool = false
@State var currentSetting2: Bool = false
@State var currentSetting3: Bool = false
// many more
var body: some View {
NavigationView {
Form {
// Change internal state, not settings
Toggle("Setting 1", isOn: $currentSetting1)
Toggle("Setting 2", isOn: $currentSetting2)
Toggle("Setting 3", isOn: $currentSetting3)
}
.navigationTitle("Preferences")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
// No need to do anything here
dismiss()
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
// Save current internal state to settings
setting1 = currentSetting1
setting2 = currentSetting2
setting3 = currentSetting3
dismiss()
}
}
}
.onAppear() {
// Load settings
currentSetting1 = setting1
currentSetting2 = setting2
currentSetting3 = setting3
}
}
}
}