gpt4 book ai didi

ios - 动态更新 tableview 部分中的 ImageView

转载 作者:行者123 更新时间:2023-12-01 17:46:05 25 4
gpt4 key购买 nike

我有一个包含 2 个(或更多)部分的表格 View 。我已经在其中添加了一个 ImageView,并且需要根据数组中包含的值在开始时以及在选择/取消选择单元格时更改 ImageView 。我创建了如下 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,当我最初加载表数据时,我需要以编程方式设置 ImageView 。要更改我所做的 ImageView ,
if tableViewData.contains(where: self.tags.contains) {
buttonCheck!.setImage(UIImage(named: "CheckmarkCircle"), for: .normal)
} else {
buttonCheck!.setImage(UIImage(named: "DeselectedCheckmarkCircle"), for: .normal)
}

我在 didSelectRowAt 内部调用了这个和 didDeselectRowAt方法。这里的问题是,当我从第一个部分(部分 = 0)中选择一个单元格时,它会影响到第二部分(部分 = 1)标题 ImageView 。在其他工作中,当我从第一节中选择一个单元格时,第二节的标题图像正在发生变化。我该如何解决这个问题?

最佳答案

我相信问题在于您正在覆盖 buttonCheck每次viewForHeaderInSection被调用,这意味着它将始终包含对您创建的最后一个按钮的引用。

如果您创建一个字典来保存 ImageView (其中索引是部分)会更好,就像在 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!)
}

然后在 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 的自定义 View 并考虑到 View 的可重用性。

关于ios - 动态更新 tableview 部分中的 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62262276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com