3

I want to update a UILabel within a UICollectionViewCell every second, which UICollectionView function should I be using for this?

The UILabel is coded in this way.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
cell.dayCountLabel.text = dayCount(Globals.datesArray[indexPath.item])
}

And receives data in this way.

func dayCount (dayCount: String) -> String{
    let day = dayCount
    let date2 = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd MMMM yyyy hh:mm a"
    let date1: NSDate = dateFormatter.dateFromString(day)!
    let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day], fromDate: date1, toDate: date2, options: NSCalendarOptions.init(rawValue: 0))
    let difference = String("\(abs(diffDateComponents.day))")
    return difference
}

Sorry for the rookie question.

Khoury
  • 411
  • 1
  • 4
  • 21

1 Answers1

2

In case that you have prepared data source text to display in UILabel, call reloadData function:

yourCollectionView.reloadData()

Otherwise, you will get the old text value.

Update

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseId", forIndexPath: indexPath) as! UICollectionViewCell

    //update cell subviews here 
    return cell
}

In your case you should create and return UICollectionViewCell custom subclass, where you implemented dayCountLabel, don't know your custom class name...

Evgeny Karkan
  • 8,782
  • 2
  • 32
  • 38
  • I've have that, but it doesn't update the UILabel, just the collection view – Khoury Jul 22 '16 at 00:44
  • Everything should work, because calling `reloadData` calls `cellForItemAtIndexPath` function where you setting new date to `UILabel`... – Evgeny Karkan Jul 22 '16 at 00:59
  • By the way `func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { cell.dayCountLabel.text = dayCount(Globals.datesArray[indexPath.item]) }` looks pretty weird, you should create and return cell here – Evgeny Karkan Jul 22 '16 at 01:02
  • What do you mean by create and return cell? – Khoury Jul 22 '16 at 01:03
  • Actually, just set a timer to collectionview.reloadData() for every second, it works, but makes the UI very slow, but hey, it works. Thanks – Khoury Jul 22 '16 at 01:13
  • 1
    Please note that creating `NSDateFormatter` instance is a time consuming operation, that is why I guess you experiencing slow UI performance. Find time to check good practice using it http://stackoverflow.com/questions/28504589/whats-the-best-practice-for-nsdateformatter-in-swift – Evgeny Karkan Jul 22 '16 at 01:16