2016-02-27 80 views
0

我知道單元格正在被重用,因此當單元格被再次呈現時,if語句出現問題。但我不明白爲什麼if語句會導致單元格在滾動時發生更改。TableView單元格在滾動時發生變化

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("ExploreTableViewCell", forIndexPath: indexPath) as! ExploreTableViewCell 

    // Configure the cell 
    let rowIndex = self.dataArray.count - (indexPath.row + 1) 
    let newsRowObj = self.dataArray[rowIndex] as NewsHeadline 
    cell.newsTitle.text = newsRowObj.source 

    if (newsRowObj.source == "reddit") { 
     cell.newsTitle.textColor = UIColor.redColor() 
    } 
    return cell 
} 

source == "reddit"文本設置爲紅色。但是當我向後滾動時,細胞會隨機變成紅色。

+0

我認爲給出的答案都是有效的,但我更喜歡使用'prepreForReuse()'。在那裏你可以告訴細胞原本應該是什麼樣子。 – Eendje

回答

0
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("ExploreTableViewCell", forIndexPath: indexPath) as! ExploreTableViewCell 
// Configure the cell 
    let rowIndex = self.dataArray.count - (indexPath.row + 1) 
    let newsRowObj = self.dataArray[rowIndex] as NewsHeadline 
    cell.newsTitle.text = newsRowObj.source 

    if (newsRowObj.source == "reddit") { 
     cell.newsTitle.textColor = UIColor.redColor() 
    } 
    else{ 
     cell.newsTitle.textColor = UIColor.blackColor() 
    } 
    return cell 
} 
+0

它爲你工作嗎?讓我知道???? –

2

這是因爲您正在重新使用某些「reddit」單元而未處理新單元格未處理的情況。您需要在設置textColor的地方添加一個else回到原始顏色。