SwiftUI change background color of a button inside a scrollview

落爺英雄遲暮 提交于 2020-03-03 08:07:42

问题


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)

    }
}

回答1:


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)
        }
    }
}



回答2:


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)
        }
    }
}



回答3:


You can change Button background Color on click using below code

struct ContentView: View {

    @State var isSelected : Bool = false
    var body: some View {

        VStack {
            Button(action: {
                self.isSelected.toggle()
            }){
                Text("State")
                    .foregroundColor(.white)
            }
            .frame(width: 130, height: 50)
            .background(self.isSelected ? Color.red : Color.blue)
        }
    }
}


来源:https://stackoverflow.com/questions/59984847/swiftui-change-background-color-of-a-button-inside-a-scrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!