我想创建一个方形按钮网格,我可以单击/点击在黑色和白色之间切换。 作为中间点,我正在创建一行按钮来执行此操作 - 请参阅下面的代码。 但是当我点击其中一个按钮时,所有按钮都会一起切换。 我不明白为什么这是因为我每个单元格都有一个状态变量?
struct ContentView: View {
var body: some View {
ZStack {
Color.green
.edgesIgnoringSafeArea(.all)
RowOfCellsView(string: "X.X.X.X")
}
}
}
struct Cell: Identifiable {
var id: Int
var state: Bool
}
struct RowOfCellsView: View {
var string: String
var cells: [Cell] {
string.map { Cell(id: 1, state: $0 == ".") }
}
var body: some View {
HStack {
ForEach(cells) { cell in
CellView(isBlack: cell.state, symbol: "Q")
}
}
}
}
struct CellView: View {
@State var isBlack: Bool
@State var symbol: String
var body: some View {
Button(action: { self.isBlack.toggle() }) {
Text("")
.font(.largeTitle)
.frame(width: 40, height: 40)
.aspectRatio(1, contentMode: .fill)
}
.background(isBlack ? Color.black : Color.white)
}
}
最佳答案
啊哈 - 刚刚注意到我将所有单元格的 id 设置为 1 - 这就是问题所在! 因此需要有一种方法为每个 Cell 拥有不同的 id。
例如可以这样做:
string.enumerated().map { Cell(id: $0.0, state: $0.1 == ".") }
关于swift - 如何停止所有 SWIFTUI 按钮一起切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402494/