更改具有较早日期的单元格的背景颜色
To change the background color of the cells with the earlier date
每个单元格都包含日期和信息(文本)。默认情况下,排序是倒序的。它按时间的倒序排列。我想在当前日期之前的单元格中更改单元格的背景颜色。
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
let today = NSDate()
每次调用它时(实际上)都会有所不同,因为它会及时获得调用它的确切时刻的 NSDate,直至 sub-milliseconds。此外,使用 NSDate 方法 isEqualToDate:
进行日期比较,因为 ==
只会比较对象引用。所以你的问题是 if today == (stores.date)
总是会因为两个原因而失败。
尝试使用不太准确的日期进行比较,也许精确到当天。您可以使用 NSDateComponents
从 NSDate 中删除时间。
您的日期比较有误。使用 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
每个单元格都包含日期和信息(文本)。默认情况下,排序是倒序的。它按时间的倒序排列。我想在当前日期之前的单元格中更改单元格的背景颜色。
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
let today = NSDate()
每次调用它时(实际上)都会有所不同,因为它会及时获得调用它的确切时刻的 NSDate,直至 sub-milliseconds。此外,使用 NSDate 方法 isEqualToDate:
进行日期比较,因为 ==
只会比较对象引用。所以你的问题是 if today == (stores.date)
总是会因为两个原因而失败。
尝试使用不太准确的日期进行比较,也许精确到当天。您可以使用 NSDateComponents
从 NSDate 中删除时间。
您的日期比较有误。使用 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