Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI change background color of a button inside a scrollview

am trying to change the color of the button according to the isSelected state but not working

struct Box: Identifiable  {
    var id: Int
    var title: String
    @State var isSelected: Bool
}

struct BoxView: View {
    var box: Box
    var body: some View{
        Button(action: {
            self.box.isSelected.toggle()
        }){
            Text(box.title)
                .foregroundColor(.white)
        }
    .frame(width: 130, height: 50)
        .background(self.box.isSelected ? Color.red : Color.blue)
    .cornerRadius(25)
    .shadow(radius: 10)
    .padding(10)

    }
}
like image 305
ialyzaafan Avatar asked Dec 14 '25 03:12

ialyzaafan


2 Answers

Try this way.

struct Box: Identifiable  {
    var id: Int
    var title: String
}

struct BoxView: View {

    var box: Box

    @State var selectedBtn: Int = 1

    var body: some View {
        ForEach((1...10).reversed(), id: \.self) { item in
            Button(action: {
                self.selectedBtn = item
            }){
                Text(self.box.title)
                    .foregroundColor(.white)
            }
            .frame(width: 130, height: 50)
            .background(self.selectedBtn == item ? Color.red : Color.blue)
            .cornerRadius(25)
            .shadow(radius: 10)
            .padding(10)
        }
    }
}
like image 128
shraddha11 Avatar answered Dec 16 '25 19:12

shraddha11


you can also observe when value change like this way.

class Box: ObservableObject {
    let objectWillChange = ObservableObjectPublisher()
    var isSelected = false { willSet { objectWillChange.send() } }
}

    struct ContentView: View {
    @ObservedObject var box = Box()
    var body: some View {
        VStack{
            Button(action: {
                self.box.isSelected.toggle()
            }){
                Text("tap")
                    .foregroundColor(.white)
            }
            .background(box.isSelected ?? false ? Color.red : Color.blue)
            .cornerRadius(25)
            .shadow(radius: 10)
            .padding(10)
        }
    }
}
like image 41
Ruchi Makadia Avatar answered Dec 16 '25 20:12

Ruchi Makadia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!