2016-03-15 79 views
1

我有下面的代码在我的表视图控制器:为什么有些细胞即使不符合条件也会被修改?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = self.tableView.dequeueReusableCellWithIdentifier("itemCell") as! ItemTableViewCell 
     cell.itemTitle.text = sortedItems[sortedArray[indexPath.section]]![indexPath.row].itemTitle 
     cell.itemType.backgroundColor = sortedItems[sortedArray[indexPath.section]]![indexPath.row].itemColor() 

     // Darkening cells 
     if /*certain condition is met*/ { 
      cell.backgroundColor = .redColor() //this colors other cells while scrolling which shouldn't happen 
      cell.itemTitle.text = "Hello" //this is applied correctly, but why? 

     } 
     return cell 
    } 

正如你可以在“意见”,这将标题代码中看到了正确的应用,而着色单元并非如此。为什么是这样?它与出队的细胞有什么关系?我怎样才能避免这种行为,以便能够对某些单元格进行着色?

+1

实际上细胞的背景颜色变成了变化,但是你无法实现,因为你的itemType背单元的背景颜色。改变cell.itemType.backgroundColor当某些条件满足,那么它会正常工作。 – iMuzahid

回答

2

表格单元在离开屏幕时被重用。因此你必须假设他们已经从另一个单元中“遗留”了数据。因此,您需要将它们重置为已知状态。在你的情况下,最简单的方法就是处理else的情况。

 if /*certain condition is met*/ { 
      cell.backgroundColor = .redColor() //this colors other cells while scrolling which shouldn't happen 
      cell.itemTitle.text = "Hello" //this is applied correctly, but why? 

     } else { 
      cell.backgroundColor = .whiteColor() // whatever the default color is 
      cell.itemTitle.text = "" 
     } 
+0

哦,大声笑,我怎么会错过:p谢谢!该死的... – cyril

相关问题