2016-03-15 23 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

相關問題