Ben
Ben

Reputation: 4867

Animate the changing of data in a collectionView

I'd like to animate a change in my UICollectionView. I have the collectionView as an @IBOutlet:

@IBOutlet weak var collectionView: UICollectionView!

And the collection view reloads (so I can change the alpha of each cell) like this:

var bulkAwardMode = false;

@IBAction func bulkAwardToggleClicked(sender: UIButton) {
    if(bulkAwardMode == false) {
        bulkAwardMode = true
    } else {
        bulkAwardMode = false
    }
    dispatch_async(dispatch_get_main_queue(), {
        self.collectionView.reloadData()
    })
}

However as this is not animated, I tried changing the reloadData() line to self.collectionView.reloadSections(NSIndexSet(index: 0)), however this just causes a crash with the error attempt to create view animation for nil view.

I'm clearly doing something wrong, but I'm not quite sure what. I did also try putting the code in a UIView.animateWithDuration block, but that also failed.

Upvotes: 2

Views: 6281

Answers (2)

user5724238
user5724238

Reputation: 27

You can try:

collectionView.performBatchUpdates({ () -> Void in
   // here you can insert ,delete and animate cells
}) { (success) -> Void in    
   //completion block
}

Upvotes: 2

Edward Laurence
Edward Laurence

Reputation: 1

Using the UITableViewDelegate

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath) {
     UIView.animateWithDuration(0.4, animations: { () -> Void in
            cell.alpha = self.bulkAwardMode
        })
}

This function is called when you reload Data.

Otherwise, you could get the visible cells :

@IBAction func bulkAwardToggleClicked(sender: UIButton) {
    if(bulkAwardMode == false) {
        bulkAwardMode = true
    } else {
        bulkAwardMode = false
    }
    var visibleCells = tableView.visibleCells
    for cell in visibleCells {
          UIView.animateWithDuration(0.4, animations: { () -> Void in
             cell.alpha = self.bulkAwardMode
          })
    }
}

Upvotes: 0

Related Questions