Reputation: 1652
How can elements be added dynamically to an UICollectionView as they are loaded into memory from an REST service?
Right now I'm calling
.reloadData()
on my UICollectionView IBOutlet, but I do not believe that this is best practice.
I've tried with performBatchUpdate, but I didn't manage to get it to work.
self.photoCollView.performBatchUpdates({
self.photoCollView.insertItemsAtIndexPaths(NSArray(object: photo) as [AnyObject])
}, completion: nil)
Here I'm trying to insert a photo object into the photoCollView which is an IBOutlet of UICollectionVIew.
@IBOutlet var photoCollView: UICollectionView!
I would appreciate an example.
Upvotes: 1
Views: 1949
Reputation: 1652
I found the solution. This is my connection to the UICollectionView
@IBOutlet var photoCollView: UICollectionView!
My Photo array is a simple Swift collection of Photo objects
var photos = [Photo]()
which is a simple class
class Photo {
let name: String
let url: String
init(name:String, url:String){
self.name = name
self.url = url
}
}
And this is how I added elements to this collectionView without the use of reloadData() method.
self.photoCollView.performBatchUpdates({
let lastItem = self.photos.count
self.photos.append(photo)
let indexPaths = let indexPaths = map(lastItem..<self.photos.count)
{
NSIndexPath(forItem: $0, inSection: 0)
}
, completion: nil)
Unfortunately I doesn't know exactly whats happening as I'm rather new to the Swift language. But from what I can understand I'm holding on to the array count before adding a new element. Then I'm invoking map with two arguments, the old count and the new one. Inside the map closure a new NSIndexPath
is created inSection: 0
, which is what I want, because right now I'm only holding 1 section all together.
Those two things I can't understand is what lastItem..<self.photos.count>
and forItem: $0
does.
Upvotes: 2
Reputation: 1625
There's many approachs, you can use reloadData() function if you are doing small amount of changes. How small they are, you need to do a performance test.
Another approach to do is perform batch updates, they can be "segmented" in small amounts, you don't need to input all the data which came from the rest service in one input. Check more about it in the CollectionView Programing Guide by Apple
By the way, the reload data can deal with it pretty good, it's up to you and your needs.
Upvotes: 0