SwiftUI更改滚动视图内按钮的背景颜色

时间:2020-01-30 11:20:20

标签: ios swift xcode scrollview swiftui

试图根据isSelected状态更改按钮的颜色,但不起作用

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)

    }
}

3 个答案:

答案 0 :(得分:5)

尝试这种方式。

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

答案 1 :(得分:3)

您还可以像这样观察值何时发生变化。

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

答案 2 :(得分:2)

您可以使用以下代码在点击时更改Button背景Color

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