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

时间:2015-12-11 10:39:30

标签: ios swift uitableview xcode7 tableviewcell

当我在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")
        }
    }
}

3 个答案:

答案 0 :(得分:2)

  

受影响的细胞也会改变其形象。它必须是关于重用细胞的东西

那是对的!原因是您只将Ingr_Uncheck图像设置为全新的单元格。如果一个单元格被重用,你就可以跳过设置图像,保留之前设置的图像。

设置Ingr_CheckIngr_Uncheck图片的决定需要根据表格模型的状态来完成。

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

现在,将正确的图像设置为新的和重复使用的单元格,确保重复使用先前检查的单元格不会更改视觉效果。

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

答案 1 :(得分:1)

你不能用" =="

比较2 uiimage
if(cell.imageView?.image == UIImage(named: "Ingr_Uncheck"))

使用此

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

答案 2 :(得分:0)

您可以通过两种方式解决此问题。将图片设置为nil cellForRow

cell.imageView?.image = nil

或者,如果您有单元格的自定义类,请执行

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

 }

使用nil或默认图像重置

相关问题