skip to Main Content

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")
    }
}

2

Answers


  1. 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 other variants, "more smart/heavy/generic/etc", are also available.

    Thanks to @AgentBilly, here is one of them:

    .onChange(of: [width, height]) { _ in
        print("Changed")
    }
    
    Login or Signup to reply.
  2. 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")
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search