RGhate
RGhate

Reputation: 63

How to change Button border color when clicked in SwiftUI

I need to display 3 Buttons in a row with a default border color of the button(say green). And based on which button amongst the three is clicked I need to change its border colour (to red) to highlight that button. SwiftUI does not allow to pass button object(self) in action handler (like 'sender' in Swift). Is there a way to toggle the border of all three buttons based on which one is selected?

HStack {
    Button(action: {
        border(Color.red, width: 1)    // This doesn't work
    }
    , label: {
        Text("Option 1")
    }).border(Color.green, width: 1)

    Button(action: {
        border(Color.red, width: 1)    
    }
    , label: {
        Text("Option 2")
    }).border(Color.green, width: 1)

    Button(action: {
        border(Color.red, width: 1)    
    }
    , label: {
        Text("Option 3")
    }).border(Color.green, width: 1)

}

Upvotes: 0

Views: 3149

Answers (1)

nicksarno
nicksarno

Reputation: 4235

The solution should look something like this:

@State var selectedButton: Int = 1

var body: some View {
    HStack {
        Button(action: {
            selectedButton = 1
        }
        , label: {
            Text("Option 2")
        })
        .border(selectedButton == 1 ? Color.red : Color.green, width: 1)

        Button(action: {
            selectedButton = 2
        }
        , label: {
            Text("Option 2")
        })
        .border(selectedButton == 2 ? Color.red : Color.green, width: 1)

        Button(action: {
            selectedButton = 3
        }
        , label: {
            Text("Option 3")
        })
        .border(selectedButton == 3 ? Color.red : Color.green, width: 1)

    }
}

Upvotes: 2

Related Questions