【发布时间】:2019-08-07 21:27:40
【问题描述】:
我想创建一个方形按钮网格,我可以单击/点击以在黑色和白色之间切换。 作为中途点,我正在创建一排按钮来执行此操作 - 请参见下面的代码。 但是当我点击其中一个时,所有按钮都会一起切换。 我不明白为什么这是因为每个 Cell 都有一个状态变量?
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)
}
}
【问题讨论】: