【问题标题】:Table view cell get initial value after scrolling滚动后表格视图单元格获取初始值
【发布时间】:2019-02-27 08:03:07
【问题描述】:

我有一个表格视图和 10 个不同的原型单元格。我使用故事板并为每个单元格创建了自定义 UITableCell 类。 CheckBoxCell 中有一个复选框。我根据选项计数在循环中创建了这些复选框。

问题是,在我选中一个复选框后,复选框值会发生变化,但是当我向上或向下滚动表格视图时,复选框值会随着初始值而变化。

我调查了stackoverflow中的一些问题。我遇到了这个问题,因为每次滚动后 dequeReusebleCell 工作并重新创建队列中的单元格。我尝试使用这些解决方案,但无法成功。

我是 Swift 的新手,我不知道如何解决这个问题。 有人可以告诉我如何解决这个问题以及正确的方法是什么?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let object = surveyDetailArray.first!.elements[indexPath.row]
switch object.type {

    case CellConfig.checkbox.rawValue:

     let cell = tableView.dequeueReusableCell(withIdentifier: "CheckboxCell", for: indexPath) as! CheckboxCell

     let object = surveyDetailArray.first!.elements[indexPath.row]

     for label in object.options {

            cell.checkbox = BEMCheckBox()
            cell.checkbox.onAnimationType = .bounce
            cell.checkbox.offAnimationType = .bounce
            cell.checkbox.boxType = .square
            cell.checkbox.onFillColor = .red
            cell.checkbox.offFillColor = .white
            cell.checkbox.onCheckColor = .white
            cell.checkbox.delegate = self
            cell.checkbox.tag = label.id

            cell.contentView.addSubview(cell.checkbox)
      }

  return cell
  }

【问题讨论】:

  • 这段代码无法编译,没有任何意义。在每次调用cellForRowAt——并且这个方法被非常频繁地调用——一个或多个新的复选框被添加到单元格中。我建议在 Interface Builder 中设计单元格。要保留复选框的状态,您必须将其保存在数据模型中。
  • dequeue 方法将重用一个可用的单元格,但它不会在第一次创建和使用它时清除其中的内容。因此,您需要确保仅在以前未使用过该单元格的情况下创建并添加一个新复选框,并确保每次都正确设置该值。不要依赖任何默认(非状态)值。

标签: swift uitableview


【解决方案1】:

在您的问题中,单元格正在出队并恢复到旧状态,这显然会因为 dequeReusableCell 而发生, 现在对于解决方案,您应该使用模型来存储不同复选框和 cellforRowAt 的状态 根据模型添加复选框持久性的代码,当您启用复选框时, 更改模型中变量的值并将其保留在您的 cellForRowAt 代码中。我添加了一个小例子以供您理解,希望对您有所帮助。

代码

Struct ButtonsStates {
   var isButtonEnabled : Bool = false 
}

// In your ViewController use the above model for saving buttonValues
   var buttonStates : [ButtonStates]? // initialize as many as the rows

// in cellForRowAt 
   guard let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as? ExampleCell else { return fatalError("") }

 // here if the cell is dequeued still when cell will again be visible then this condition will be checked 
  cell.customButton.isSelected = buttonStates[indexPath.row].isButtonEnabled
   return cell

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 2019-04-07
    • 2021-11-18
    • 2021-05-29
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多