Home > Back-end >  .onChange(of: ) for multiple @State properties at once?
.onChange(of: ) for multiple @State properties at once?

Time:07-19

Is there a way I can use .onChange to detect the change of multiple @State properties at once? I know I could just chain 2 .onChange modifiers but it would be better if I could just detect all at once and run some code.

@State private var width = 0.0
@State private var height = 0.0

var body: some View {
    Button(action: {
        width  = 0.1
    }, label: {
        Text("Width   0.1")
    })
    .onChange(of: width) { _ in 
        print("Changed")
    }
}

CodePudding user response:

For this case here is the simplest I think

.onChange(of: width   height) { _ in
    print("Changed")
}

Update: as I wrote above is 'simplest' (and for specific scenarios can be enough), but of course any other variant "more smart/heavy/generic/etc" are also available.

Thanks to @AgentBilly, here is one of them:

.onChange(of: [width, height]) { _ in
    print("Changed")
}

CodePudding user response:

Create a struct and use that as your state:

struct Size {
  var width: Double = 0 
  var height: Double = 0

  // mutating func exampleMethod(){
  // }
}

Then init it as your state:

@State var size = Size()

var body: some View {
    Button(action: {
        size.width  = 0.1
    }) {
        Text("Width   0.1")
    }
    .onChange(of: size) { newSize in 
        print("Changed")
    }
}
  • Related