2017-08-18 48 views
2

我有一個UITableViewController顯示自定義單元格與幾個標籤和自定義UIView。在tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)方法中,當單元格被重用時(它們看起來完全是隨機的),顏色似乎沒有被重置。我怎樣才能解決這個問題?顯示不正確的值的自定義UITableViewCell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let historyEntry = allHistoryEntries[indexPath.section].histories![indexPath.row] 

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HistoryCell 

    cell.dateLabel.text = "\(getDayFrom(date: (historyEntry.beginDate)!))" 

    let highestBac = getHighestBac(history: historyEntry) 
    cell.highestBacLabel.text = "Høyeste promille " + String(describing: Double(highestBac).roundTo(places: 2)) 

    cell.costLabel.text = String(describing: getNorwegianDayFrom(date: (historyEntry.beginDate!))) + " brukte du " + String(describing: calculateTotalCostBy(history: historyEntry)) + ",-" 

    let goal = Double(AppDelegate.getUserData()?.goalPromille ?? 0.0) 
    let red = UIColor(red: 193/255.0, green: 26/255.0, blue: 26/255.0, alpha: 1.0) 
    let green = UIColor(red:26/255.0, green: 193/255.0, blue: 73/255.0, alpha: 1.0) 

    let color = highestBac > goal ? red : green 

    cell.highestBacLabel.textColor = color 
    cell.circleView.ringColor = color 

    return cell 
} 

這是顯示顏色的圖像。預期的行爲是應該使用紅色或綠色,而不是組合。

UPDATE: 只有ringColor顯示錯誤的顏色。

enter image description here

+0

您是什麼意思的「當細胞被重複使用」?你如何重複使用它們? –

+0

我可能是錯的,但根據我的理解,細胞在不再出現在屏幕上時會被重用,例如,如果有更多細胞可以放入屏幕中。所以我懷疑這個單元格是在tableview滾動時重用的,它保留了最初設置的顏色。 – mrfonnes

+0

「textColor」是否正確更改,但「circleView.ringColor」有時不正確? (這是圖片顯示的內容,我只是問這個行爲是否一致) –

回答

0

所以這個問題在我的CircleView類中缺少呼叫setNeedsDisplay()。感謝威廉GP。

0

如果需要重新設定的值,如textColor當小區被出隊用於再使用可以像這樣覆蓋在UITableViewCell子類(HistoryCell)的prepareForReuse方法:

override func prepareForReuse() { 
    super.prepareForReuse() 
    //Reset label color back to default green 
    let green = UIColor(red:26/255.0, green: 193/255.0, blue: 73/255.0, alpha: 1.0) 
    self.highestBacLabel.textColor = green 
} 
+0

我更新了我的問題,以便更具體。沒有默認顏色,顏色由highestBac>目標確定。滾動時顏色顯示爲隨機。 – mrfonnes

+0

@SimenFonnes你可以顯示你的'getHighestBac'和你的'AppDelegate.getUserData()'函數的代碼嗎?我猜你在那裏有一些問題。乍一看,爲什麼不只是獲得'getUserData()。goalPromille'的單個引用,可能在'viewDidLoad'中,這樣你就不必一直回到AppDelegate併爲每個單元調用該函數? – creeperspeak

1

如果沒有默認顏色,請重置顏色以用prepareForReuse()清除。此功能必須在您的HistoryCell類中

override func prepareForReuse() { 
    super.prepareForReuse() 
    //Reset label to clear color 
    self.highestBacLabel.textColor = UIColor.clear 
} 
相關問題