How manipulate code from an embedded view?

Hello all,

I’ve only been at this for a few months, so I apologize if this has been answered elsewhere.

I’ve created a custom toggle button within my app’s main view. When tapped, it runs a simple isPressed.toggle() function, which then changes some details about the button. Other parts of the view are executing commands via .onChange(of: isPressed...) or waiting on a variable to be updated via isPressed.toggle() function.

When I extract the button to it’s own view, it can no longer be used to update the state of a variable in the main view, nor can an element in the main view use the .onChange function.

Example:

 Button(action: {
     customToggle.toggle()
 }, label:  {
     Text("Button Label")
                if customToggle == false {
                     *code*
                } else {
                     *code*
                }
           }

Can someone point me in the right direction?

Your extracted ButtonView(?) needs to have a @Binding variable for customToggle which Binds it back to your @State variable in the View in which the Button is used.

So you would do something like this:

struct ContentView: View {
    @State private var customToggle = false

    var body: some View {
        VStack(spacing: 30) {
            Text(customToggle ? "True" : "False")
                .padding()
            ButtonView(customToggle: $customToggle)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

//  Extracted Button View
struct ButtonView: View {
    @Binding var customToggle: Bool

    var body: some View {
        Button(action: {
            customToggle.toggle()
        }) {
            Text("Button Label")
            if customToggle == false {
                // Code
            } else {
                // Code
            }
        }
    }
}

Holy cow, man - you just made my day. Thank you!

1 Like