动态更新tableview部分中的ImageView

问题描述 投票:1回答:2

我有一个包含2个(或更多)部分的表格视图。我已经在其中添加了一个ImageView,并且需要根据开始和选择/取消选择单元格时数组中包含的值来更改图像视图。我创建了如下视图,

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,并且当我最初加载表数据时,需要以编程方式设置图像视图。要更改我所做的图像视图,

if tableViewData.contains(where: self.tags.contains) {
   buttonCheck!.setImage(UIImage(named: "CheckmarkCircle"), for: .normal)
} else {
   buttonCheck!.setImage(UIImage(named: "DeselectedCheckmarkCircle"), for: .normal)
}

我在didSelectRowAtdidDeselectRowAt方法中称呼它。这里的问题是,当我从第一个节(section = 0)中选择一个单元格时,它会影响第二个节(section = 1)标题图像视图。在其他工作中,当我从第一节中选择一个单元格时,第二节的标题图像正在更改。我该如何解决?

ios swift tableview
2个回答
2
投票

[我相信问题是,每次调用buttonCheck时,您都将覆盖viewForHeaderInSection,这意味着它将始终保留对您创建的最后一个按钮的引用。

如果您创建一个字典来保存图像视图(索引是该部分),则更好,像在控制器作用域上这样:

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!)
}

然后在didSelectdidDeselect上更新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)
}

[请考虑到性能的明智选择,这可能不是最佳解决方案。最好创建一个扩展了UITableViewHeaderFooterView的自定义视图,并考虑到视图的可重用性。


2
投票

您可以采用多种方法。一种快速而肮脏的方法是只调用tableView.reloadData(),这将迫使TableView中的每个元素都重新加载来自DataSource的当前数据。

如果您想采用性能更高的方法,则可以选择仅通过循环遍历节标题来重新加载节标题。这在this问题中得到了很好的回答。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.