我有一个有2个(或更多)节的表视图。 我添加了一个ImageView到它中,并且需要根据在开始时和选择/取消选择单元格时数组中包含的值来更改image view。 我创建了如下视图,
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let viewHeader = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 40))
buttonCheck = UIButton(type: .custom)
buttonCheck!.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
buttonCheck!.tag = section
buttonCheck!.addTarget(self, action: #selector(tapSection(sender:)), for: .touchUpInside)
viewHeader.addSubview(buttonCheck!)
}
这样可以很好地添加ImageView,并且当我最初加载表数据时,我需要以编程方式设置image视图。 要更改我所做的图像视图,
if tableViewData.contains(where: self.tags.contains) {
buttonCheck!.setImage(UIImage(named: "CheckmarkCircle"), for: .normal)
} else {
buttonCheck!.setImage(UIImage(named: "DeselectedCheckmarkCircle"), for: .normal)
}
我将其内部称为DidSelectRowat
和DidDesElectroWat
方法。 这里的问题是,当我从第一节(section=0)中选择一个单元格时,它会影响到第二节(section=1)的标题图像视图。 在其他工作中,当我从第一节中选择一个单元格时,第二节的标题图像会发生变化。 我该怎么解决这个问题?
我认为问题在于,每次调用ViewForHeaderInSection
时,您都在重写ButtonCheck
,这意味着它将始终保持对您创建的最后一个按钮的引用。
最好创建一个字典来保存imageviews(其中索引是节),如controller作用域中所示:
var imageViews: [Int: UIButton] = [:]
然后将ViewForHeaderInSection
更改为:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let viewHeader = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 40))
let buttonCheck = UIButton(type: .custom)
buttonCheck!.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
buttonCheck!.tag = section
buttonCheck!.addTarget(self, action: #selector(tapSection(sender:)), for: .touchUpInside)
imageViews[section] = buttonCheck
viewHeader.addSubview(buttonCheck!)
}
然后在DidSelect
和DidDeselect
上更新ImageView:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
imageViews[indexPath.section]?.setImage(UIImage(named: "CheckmarkCircle"), for: .normal)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
imageViews[indexPath.section]?.setImage(UIImage(named: "DeselectedCheckmarkCircle"), for: .normal)
}
请考虑性能,这可能不是最好的解决方案。 最好创建一个扩展UITableVieweAderFooterView的自定义视图,并考虑视图的可重用性。
您可以采取多种方法。 快速而肮脏的方法是只调用TableView.reloadData()
,这将强制使用数据源中的当前数据重新加载TableView中的每个元素。
如果您想采取性能更好的方法,可以选择仅通过循环来重新加载节头。 这一点在这个问题中得到了很好的回答。 祝你好运。