Most efficient way to call a function upon variable state change

Hi,

I have a button view that is used in many different ways in an app that I'm working on. One of the ways it is used is in an account creation form. Since the button is in a child view, the action: { } button function isn't available in the view where the input field variables are. I could import the class with the function to the button view but I don't want to pass the input field variables into the button view. I tried binding a boolean variable to the button view and checked for it's state change in the parent view using .onChange(), but the use case for that I found was depreciated and I'm unable to revert the state of the variable in the .onChange function.

To reiterate, in a main view, I need to call a function in a given class and pass variables to it, upon a button being pressed in a child view. Any help would be greatly appreciated.

It would be much simpler to explain if you posted the code you have tried with Binding.

Is it what you are looking for ?

struct TestButton: View {
    
    @Binding var isSelected: Bool
    
    var body: some View {
        Button(action: {
            self.isSelected.toggle()
        }) {
            Text("Change")
        }
    }
}

struct ContentView: View {
    
    @State var buttonState = false
    @State var someTextToDisplay = "no state defined yet"
    
    func forStateOn() {
        someTextToDisplay = "State is on"
    }

    func forStateOff() {
        someTextToDisplay = "State is off"
    }

    var body: some View {
        VStack {
            Text(buttonState ? "selected" : "unselected")
            TestButton(isSelected: $buttonState)
            Text(someTextToDisplay)
        }
        .onChange(of: buttonState) { oldState, newState in
            if newState {
                forStateOn()
            } else {
                forStateOff()
            }
        }
    }
}
Most efficient way to call a function upon variable state change
 
 
Q