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
当用户按下“保存”按钮时,将当前值保存到设置。像这样: