ios - 更改日期较早的单元格的背景颜色

标签 ios swift nsdate uitableview

每个单元格包含日期和信息(文本)。默认情况下,排序是逆序的。它是按照时间的倒序排列的。我想更改当前日期之前单元格中单元格的背景颜色。

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/

相关文章:

ios - Xcode 中的 AudioPlayer 快进

ios - 使用 Swift 4 将 Pdf、Docx 和图像文件上传到服务器

swift - swift 2 调用中缺少参数选项参数

ios - NSDateFormatter 在时间分析器中太慢

iphone - 如何以编程方式构建本地化日历月份名称的 NSArray?

ios - 防止顶部 UiTableViewCell 滚动

android - 最新 KMM 中 Cocoapod 的 `./gradlew packForXcode` 替换是什么?

iphone - 如何在UILabel文本下划线-iPhone App

ios - 'CALayer 位置包含 NaN : [nan nan]' on UIScrollView

ios - 如何从当前日期到特定 NSDate 进行倒计时?