每个单元格包含日期和信息(文本)。默认情况下,排序是逆序的。它是按照时间的倒序排列的。我想更改当前日期之前单元格中单元格的背景颜色。
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
最佳答案
您的日期比较是错误的。使用 NSCalendar 来按天比较 NSDate。这里描述了很好的 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
}
//...
}
在代码中使用此扩展:
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
关于ios - 更改日期较早的单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660441/