ios - 如何阻止我的 tableView 单元格重复使用其中的按钮?

标签 ios swift uitableview tableview swift-protocols

我在协议(protocol)中有一个函数,它接受 TableViewcell 作为参数。

protocol GoingButtonDelegate {
    func goingButtonPressed(cell: TableViewCell)
}

class TableViewCell: UITableViewCell {
    // Outlets
    @IBOutlet weak var goingButton: UIButton!

    var delegate: GoingButtonDelegate?

    @IBAction func goingButtonTapped(_ sender: Any) {
        delegate?.goingButtonPressed(cell: self)  
    }

然后我转到 ViewController 并实现委托(delegate)及其功能,即在点击时更改按钮的图像。 “goingSelected”是绿色图像,“goingDeselected”是红色图像。

这一切都很好,当点击单元格的按钮时,它会从红色变为绿色,反之亦然。但是,当单元格被重用时,单元格的按钮状态将保持不变,并为进入 View 的新行重用。有什么办法可以阻止这种情况发生吗?

 extension ViewController: GoingButtonDelegate {
    func goingButtonPressed(cell: TableViewCell) {
        cell.goingButton.isSelected = !cell.goingButton.isSelected

        if cell.goingButton.isSelected == true {
            cell.goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)
        } else if cell.goingButton.isSelected == false {
            cell.goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
        }
    }
}

最佳答案

有可能

直接替换即可

let cell = tableView.dequeueReusableCell(withIdentifier: identifier,
  for: indexPath)

与:

let cell= Bundle.main.loadNibNamed(identifier, owner: self, options: nil)?[0]

但我认为您需要更改应用程序逻辑。

在单元类中设置图像

class TableViewCell: UITableViewCell {
  override func awakeFromNib() {
    super.awakeFromNib()
    self.goingButton.setImage(UIImage(named: "goingDeselected"), for:.normal)
    self.goingButton.setImage(UIImage(named: "goingSelected"), for:.selected)
  }
}

并在方法 goingButtonPressed(cell: TableViewCell) 中将 cell 更改为您的对象 只需设置 Bool 类型 true 或 false

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  ...
  cell.goingButton.isSelected = object.isSelected
  ...
}

关于ios - 如何阻止我的 tableView 单元格重复使用其中的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026531/

相关文章:

iphone - 编辑 UITableViewCells 的不可见行

iOS 更改父 ViewController 的 Integer/NSNumber

ios - 我怎样才能只突出显示一项?

xcode - CoreAnimation 未提交 CATranaction NSComboBox

ios - UIPageViewController 或启用分页的 UIScrollView = YES

ios - UITableView section scrollBar 的背景色怎么弄清楚?

ios - 如何在没有 StoryBoard 的情况下以编程方式将单元格添加到 CollectionView

ios - 如何更改uitableview单元格内图像的位置

ios - 侧边栏菜单不显示?

ios - 即使超过缓存控制期限限制,也会从缓存中加载值