【问题标题】:How can I stop all my SWIFTUI buttons toggling together?如何阻止我的所有 SWIFTUI 按钮一起切换?
【发布时间】: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)
  }
}

【问题讨论】:

    标签: swift button swiftui


    【解决方案1】:

    啊哈 - 刚刚注意到我将所有单元格的 id 设置为 1 - 这就是问题所在! 所以需要有一种方法为每个 Cell 设置不同的 id。

    例如可以这样做:

    string.enumerated().map { Cell(id: $0.0, state: $0.1 == ".") }
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2019-06-05
      • 2022-01-01
      • 1970-01-01
      • 2023-01-28
      • 2021-09-11
      • 1970-01-01
      • 2019-02-08
      • 2021-05-19
      相关资源
      最近更新 更多