【发布时间】:2020-10-26 19:01:13
【问题描述】:
我想将按钮着色为上面的颜色数组。例如:如果用户首先选择任何按钮,则该按钮的颜色应为橙色,如果用户选择另一个按钮,则该按钮的颜色应为绿色,依此类推。用户最多可以从 10 个按钮中选择 7 个按钮,如果选择了 7 个不同的按钮,那么它们应该有 7 种不同的颜色。
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 {
@State private var selectedButtons = [Int]()
var body: some View {
ForEach(0..<totalButtons) { index in
Button(action: {
self.updateSelectButton(value: index)
}) {
Text("Button \(index)")
}
.background(self.selectedButtons.contains(index) ? colors[index].value : Color.white)
}
}
func updateSelectButton(value: Int) {
guard value < colors.count else {
return
}
if let index = self.selectedButtons.firstIndex(of: value) {
self.selectedButtons.remove(at: index)
} else {
self.selectedButtons.append(value)
}
}
}
代码如上所示。 上面代码的问题是用户无法选择数组中的第 8、9 和 10 个按钮。用户只能选择前 7 个按钮。
【问题讨论】:
-
用户最多可以从 10 个按钮中选择 7 个按钮 这意味着在任何时候都不应选择超过 7 个按钮,对吗?如果你只选择一个按钮(比如说第 10 个),它应该有什么颜色?
-
如果您只选择第 10 个按钮,那么它应该有橙色(颜色数组中的第一项),如果选择让我们说第 4 个按钮,那么第 4 个按钮应该有绿色,依此类推。 @pawello2222
标签: ios swift xcode swiftui swift5