Changing Modifiers by Code

Hi

suppose I have 2 buttons button1 and button2 and when button2 is tapped I want to change button1 colors and it’s text, how to do that ? How to reference to button1 and change its modifiers ?

now also suppose button one was a text such as Text(“Some Text”), how to change text shown between brackets when button2 is tapped ?

Kindest Regards

In SwiftUI you have not to reference the other object, but change a State and have Button1 take this State into account.

Create a State var.

@State var button1Color : Color = .blue

Use it in Button1 modifier that sets its color, such as:

                    .foregroundColor(button1Color)

And change it in Button2 action

        Button(
            action: {
                button1Color = .red

Do the same with Text:

    @State var text1 = "Hello"

// Button1:
        Button(
            action: {
                vOffset += 20 // Any action
            }, label: {
                Text(text1)
           }
        )

// Button2
        Button(
            action: {
                text1 = "New"
            }, label: {
                Text("button2")
           }
        )

Changing Modifiers by Code
 
 
Q