如何更改SwiftUI中forEach内部动态创建的按钮的颜色

时间:2020-07-05 10:37:12

标签: ios swiftui

我想在swiftUI forEach语句中用不同的颜色更改不同按钮的颜色。更改按钮颜色时,不应更改其他按钮的颜色。我该如何实现?我的代码如下:

import SwiftUI

struct ColorModel: Identifiable {
    let value: Color
    let id = UUID()
}
let colors = [
    ColorModel(value: Color.orange),
    ColorModel(value: Color.green),
    ColorModel(value: Color.blue),
    ColorModel(value: Color.red),
    ColorModel(value: Color.yellow),
    ColorModel(value: Color.gray),
    ColorModel(value: Color.pink),
]
let totalButtons: Int = 10

struct ContentView: View {
    func updateSelectedButtons(value: Int) {
        if self.selectedButtons.contains(value) {
            if let index = self.selectedButtons.firstIndex(of: value) {
                self.selectedButtons.remove(at: index)
            }
        } else {
            if self.selectedButtons.count < 7 {
                self.selectedButtons.append(value)
            }
        }
    }
    @State private var selectedButtons: [Int] = [Int]()
    @State private var colorIndex: Int = 0
    var body: some View {
        ForEach(0 ..< totalButtons) { index in
            Button(action: {
                self.updateSelectedButtons(value: index)
                self.colorIndex += 1
            }) {
                Text("  ")
            }
            .background(self.selectedButtons.contains(index) ? colors[self.colorIndex].value : Color.white)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

struct ContentView: View {
    @State private var selectedButtons = [Int]()

    var body: some View {
        ForEach(0..<totalButtons) { index in
            Button(action: {
                self.updateSelectButton(value: index) // <- on tap update selection
            }) {
                Text("Button \(index)")
            }
            .background(self.selectedButtons.contains(index) ? colors[index].value : Color.white) // <- if index is selected set color 
        }
    }

    func updateSelectButton(value: Int) {
        guard value < colors.count else { // <- make sure you don't go outside the `colors` range
            return
        }
        if let index = self.selectedButtons.firstIndex(of: value) {
            self.selectedButtons.remove(at: index)
        } else {
            self.selectedButtons.append(value)
        }
    }
}