0

Each cell contains the date and information(text). By default, sorting is in reverse order. It is sorted in the reverse order of the time. I want to change the background color of the cells in the cell prior to the current 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
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Iden Lim
  • 117
  • 2
  • 7
  • What's your question? – rmaddy Jan 07 '16 at 16:44
  • If you have problem with date equality comparison, try `isEqualToDate` method – san Jan 07 '16 at 16:49
  • What you need is NSCalendar method isDateInToday https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/#//apple_ref/occ/instm/NSCalendar/isDateInToday: – Leo Dabus Jan 07 '16 at 17:05
  • You might be interested in this one also http://stackoverflow.com/a/34457607/2303865 – Leo Dabus Jan 07 '16 at 17:12

2 Answers2

0

let today = NSDate() will be (practically) different everytime you call it, as it gets the NSDate for the exact moment in time it was called, down to sub-milliseconds. Also, use the NSDate method isEqualToDate: for date comparison, as == will simply compare object references. So your problem is that if today == (stores.date) will always fail for two reasons.

Try having dates that are less accurate, perhaps down to the day, for this comparison. You could use NSDateComponents to remove the time from the NSDate.

0

Your date comparison is wrong. Use NSCalendar to compare NSDate by day. Good NSDate extension described here 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
    }
    //...
}

Using this extension in you code:

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
Community
  • 1
  • 1
shpasta
  • 1,913
  • 15
  • 21