【问题标题】:To change the background color of the cells with the earlier date更改具有较早日期的单元格的背景颜色
【发布时间】:2016-01-07 16:36:04
【问题描述】:

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

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

【问题讨论】:

标签: ios swift nsdate tableviewcell


【解决方案1】:

您的日期比较错误。使用 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

【讨论】:

    【解决方案2】:

    let today = NSDate() 每次调用时都会(实际上)不同,因为它会在调用它的确切时刻获取 NSDate,低至亚毫秒。此外,使用 NSDate 方法 isEqualToDate: 进行日期比较,因为 == 将简单地比较对象引用。所以你的问题是if today == (stores.date) 总是会因为两个原因而失败。

    尝试使用不太准确的日期(可能精确到当天)进行比较。您可以使用NSDateComponents 从 NSDate 中删除时间。

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2011-09-24
      • 2013-04-12
      • 2021-10-31
      相关资源
      最近更新 更多