Search code examples
swiftbuttonswiftuiviewlabel

SwiftUI, How to change one button label with multiple buttons and one Bool Condition


my problem is that I don't wanna declare multiple Bool var for these code , and i wanna change the exact button pressed Label , Not All

@State var buttonClicked : Bool

var body: some View {
    HStack {
        Text("Size")
            .fontWeight(.bold)
        Spacer()
        Button {
            self.buttonClicked.toggle()
        } label: {
            Text("US")
                .foregroundColor(buttonClicked ? .black : .gray.opacity(0.5))
                .fontWeight(.bold)
        }
        Button {
            self.buttonClicked.toggle()
        } label: {
            Text("UK")
                .foregroundColor(buttonClicked ? .black : .gray.opacity(0.5))
                .fontWeight(.bold)
        }
        Button {
            buttonClicked.toggle()
        } label: {
            Text("EU")
                .foregroundColor(buttonClicked ? .black : .gray.opacity(0.5))
                .fontWeight(.bold)
        }
    }
}

}


Solution

  • If you can set your options into something reusable like an array you can eliminate the duplicate code.

    import SwiftUI
    
    struct MultiButtonView: View {
        @State var buttonClicked : String = ""
        let options = ["US", "UK", "EU"]
        var body: some View {
            HStack {
                Text("Size")
                    .fontWeight(.bold)
                Spacer()
                ForEach(options, id:\.description) { option in
                    Button {
                        self.buttonClicked = option
                    } label: {
                        Text(option)
                            .foregroundColor(buttonClicked == option ? .black : .gray.opacity(0.5))
                            .fontWeight(.bold)
                    }
                }
            }
        }
    }