What is the best way to go about resetting state variables, using a button. I've tried a load of different funcs but none work.
I'm trying to use this button:
primaryButton: .destructive(Text("Delete")) {
Code
},secondaryButton:
.cancel()
To reset these State variables:
@State var statsValue1 = 0
@State var statsValue2 = 0
@State var statsValue3 = 0
@State var statsValue4 = 0
@State var statsValue5 = 0
@State var statsValue6 = 0
(which are in the main content view)
CodePudding user response:
How about using a view model, the @Published
property wrapper notifies about any changes of the model and the reset
function creates a new instance
struct Model {
var value1 = 0
var value2 = 0
var value3 = 0
}
class ViewModel : ObservableObject {
@Published var model = Model()
func reset() {
model = Model()
}
}
and a simple test logic in the content view
struct ContentView : View {
@StateObject var viewModel = ViewModel()
var body : some View {
VStack(spacing: 20) {
Text("Value 1: \(viewModel.model.value1)")
Text("Value 2: \(viewModel.model.value2)")
Text("Value 3: \(viewModel.model.value3)")
Divider()
Button ( "Delete", role: .destructive, action: viewModel.reset )
Button { viewModel.model.value1 = 1 } label: { Text("Increment value 1") }
Button { viewModel.model.value2 = 1 } label: { Text("Increment value 2") }
Button { viewModel.model.value3 = 1 } label: { Text("Increment value 3") }
}
}
}