gpt4 book ai didi

ios - 如何重用 UITableView 中的单元格

转载 作者:搜寻专家 更新时间:2023-11-01 05:38:17 25 4
gpt4 key购买 nike

我有一个 UITableView,其中每个单元格都有一个图像。每当我选择其中一个单元格时,我都会更改当前单元格的图像。但是当我滚动并且一个或多个单元格离开视线时,单元格会被重新创建或一些,并且默认图像再次出现。我希望更改后的图像保留在单元格上,直到 View 卸载或消失。

这是我对 UITableView 的委托(delegate)。

//UITableview delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Arecipe.IngredientArr.count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if(tableView == IngrediensTableView || tableView == ProcedureTableView)
{
print("Cell")

let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let ingredient = self.Arecipe.IngredientArr[indexPath.row]

cell.textLabel?.text = ingredient.UnitValue + " " + ingredient.UnitName + " " + ingredient.Name
cell.imageView?.image = UIImage(named: "Ingr_Uncheck")
cell.selectionStyle = .None

return cell
}

return UITableViewCell()
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row) selected")

if(tableView == IngrediensTableView || tableView == ProcedureTableView)
{
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

if(cell.imageView?.image == UIImage(named: "Ingr_Uncheck"))
{
cell.imageView?.image = UIImage(named: "Ingr_Check")
}
else
{
cell.imageView?.image = UIImage(named: "Ingr_Uncheck")
}
}
}

最佳答案

你在这里看到的是 View 回收。这允许 UITableView 更快并且使用更少的内存。

您应该将“选中”状态逻辑与单元分开。

向您的类添加一个属性,用于存储选中的 IndexPath

var checkedIndexPath:NSIndexPath?

然后将选定的索引保存在 checkedIndexPath 中。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let previousChecked = checkedIndexPath
checkedIndexPath = indexPath
tableView.reloadRowsAtIndexPaths([previousChecked, checkedIndexPath], withRowAnimation:.Automatic)
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
if indexPath == checkedIndexPath {
cell.imageView?.image = UIImage(named: "Ingr_Check")
}
else {
cell.imageView?.image = UIImage(named: "Ingr_Uncheck")
}
}

关于ios - 如何重用 UITableView 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34207286/

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