在 UITableView 中选择一个单元格,另一个单元格会受到影响

Selecting a cell in UITableView another one gets affected

当我 select UITableView 中的一个单元格时,我更改了它的图像,但是视线之外的单元格(需要向下滚动才能看到受影响的单元格)受到影响,这意味着受影响的单元格细胞也改变了它的形象。这一定是关于重复使用的单元格的问题,但我不知道为什么以及如何解决这个问题。希望大家帮帮我,谢谢

另一件事是,当单元格滚动到看不见的地方时,它不应该重置它的图像。

这是我的 UITableView 代表:

//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) {
        print("Cell")

        var cell = tableView.dequeueReusableCellWithIdentifier("Cell")

        let ingredient = self.Arecipe.IngredientArr[indexPath.row]

        if ((cell == nil)) {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
            cell!.imageView?.image = UIImage(named: "Ingr_Uncheck")
        }

        cell!.textLabel?.text = ingredient.UnitValue + " " + ingredient.UnitName + " " + ingredient.Name
        cell!.selectionStyle = .None

        return cell!
    }
    return UITableViewCell()
}

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

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

        print(cell.textLabel?.text)

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

你无法通过“==”比较 2 个 uiimage

if(cell.imageView?.image == UIImage(named: "Ingr_Uncheck"))

使用这个

if( [UIImagePNGRepresentation(cell.imageView?.image) isEqual:UIImagePNGRepresentation(UIImage(named: "Ingr_Uncheck"))] == YES)

the affected cell also change its image. It must be something about the reused cells

没错!原因是您仅将 Ingr_Uncheck 图像设置为全新的单元格。如果一个单元格被重复使用,您将跳过设置图像,保留之前在那里设置的任何内容。

设置 Ingr_CheckIngr_Uncheck 图像的决定需要根据您的 table 模型的状态来完成。

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

现在新单元格和重复使用的单元格都设置了正确的图像,确保重复使用以前检查过的单元格不会改变视觉效果。

代码 myCodeThatChecksIfRowIsChecked 需要依赖于您在 didSelectRowAtIndexPath 方法中更改的某些存储状态。这是您需要为已检查的单元格维护行号列表的地方。这也是您在决定是否应取消选中单元格时参考的列表:根据图像执行此操作不是正确的方法。

您可以通过两种方式解决这个问题。要么将图像设置为 nil cellForRow

cell.imageView?.image = nil

或者,如果您为单元格自定义了 class,请实施

override func prepareForReuse() {
    imageView?.image = nil

 }

重置为 nil 或使用默认图片