2016-01-07 38 views
0

每個單元包含的日期和信息(文本)。默認情況下,排序順序相反。它按照與時間相反的順序排序。我想在當前日期之前更改單元格中單元格的背景顏色。要改變單元格的背景色與較早的日期

的tableView的cellForRowAtIndexPath:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexpath) as! tableViewCell 
    cell.dateLabel.text = stores.date 
    cell.contentLabel.text = stores.content 

    let today = NSDate() 
    if today == (stores.date) { 
    cell.backgroundColor = UIColor.blueColor() 
    } else { 
    cell.backgroundColor = UIColor.clearColor() 
    } 

    return cell 
+0

什麼是你的問題? – rmaddy

+0

如果你有時間相等比較問題,請嘗試'isEqualToDate'方法 – san

+0

你需要的是NSCalendar方法isDateInToday https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/# // apple_ref/OCC/instm/NSCalendar/isDateInToday: –

回答

0

您的日期比較是錯誤的。使用NSCalendar來比較NSDate白天。這裏Getting the difference between two NSDates in (months/days/hours/minutes/seconds)

extension NSDate { 
    // ... 
    func daysFrom(date:NSDate) -> Int{ 
     return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day 
    } 
    //... 
} 

描述好NSDate的擴展使用該擴展在你的代碼:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexpath) as! tableViewCell 
    cell.dateLabel.text = stores.date 
    cell.contentLabel.text = stores.content 

    if (stores.date.daysFrom(NSDate()) == 0) { 
    cell.backgroundColor = UIColor.blueColor() 
    } else { 
    cell.backgroundColor = UIColor.clearColor() 
    } 

    return cell 
+0

完成!非常非常謝謝! –

0

let today = NSDate()將是(幾乎)不同,​​每次你怎麼稱呼它,因爲它得到的NSDate的確切時刻,它被稱爲,小到亞毫秒。此外,使用NSDate方法isEqualToDate:進行日期比較,因爲==將簡單比較對象引用。所以你的問題是if today == (stores.date)總是會失敗的原因有兩個。

有嘗試的日期是不準確的,可能下降到一天,這種比較。您可以使用NSDateComponents從NSDate中刪除時間。

+0

感謝。好〜! –

相關問題