I have a state variable of a struct with 2 numbers. I have a selection box for the 1st one, and a selection box for the 2nd one which should cap it at the 1st one. I implemented the capping logic with didSet. The value of the selections did change, but not the text that display the selected value for the 2nd one. Here’s the pseudo code. Any idea?
struct CustomTaskView: View {
@State private var options: MyClass {
didSet {
if options.a > options.b {
options.a = options.b
}
}
}
var body: some View {
// selection box for options.a
// selection box for options.b
// ...
Text("(options.a)")
Text("(options.b)")
}
}
2
Answers
You may have made it with spit and duct tape, but this is not how you should do it in the first place!
First of all, you need to separate the View logic from the Model logic. Then you can decide where to put the required behavior. For example, you can do it in the View like this:
Or move it to the model. Something like:
Note that these are simple demonstrations and you should check all logic based on your actually needs
You declare
@State private var options: MyClass ...
, thenyou also need to instantiate it, as shown in the example code.
Note, your code is not how SwiftUI should be used.