Swift - UICollectionView repeat (duplicate) cells

Hi I have an array with 100 pictures taken from flickr. When I use UICollectionView I show 100 cells, only 8 cells are on the screen and when I scroll down to see the next 8 they are the same as the previous ones and when I do

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!


and println ("something") it writes to the console just 8 times something, but the contents of the array are 100

I am using this:

func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int {
    return self.photosUrls.count


It makes 100 cells, but cells are always repeated ... Anyone who knows how to beat Swift in the new Xcode GM seed version?

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
    let cell: ImageCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as ImageCell
    let imgUrl = photosUrls[indexPath!.row]
    let api_url = NSURL.URLWithString(imgUrl)
    let URLReq = NSURLRequest(URL: api_url)
    let NSOpQ:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(URLReq, queue: NSOpQ, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        if(error == nil){
            cell.theWPImage!.image = UIImage(data: data)
    return cell



source to share

2 answers

I think you don't understand how the delegate UITableView

and methods work UICollectionView


iOS won't load 100 cells at a time because it will be very slow and won't have a good user experience. Thus, the cellForItemAtIndexPath

or methods cellForRowAtIndexPath

are only called when the cells are displayed on the screen.

Whenever you scroll down, you will see that the method cellForItemAtIndexPath

is called again to create new cells. If you put the code println(indexPath.row)

inside cellForItemAtIndexPath

, you will see that the cell number is printed repeatedly as you scroll up or down.

If you see the same cells after scrolling down, it might be related to your code on cellForItemAtIndexPath

. I can't help you if you haven't entered the complete source code above. Or it could be a bug in UICollectionView

GM for Xcode seeds.

How do I try the same project in XCode 6 Beta 7 and report back? I have a problem with UICollectionView in XCode GM. This is due to the limitation. See: iOS 8 GM Doesn't Update Collection View Constraints I'm using XCode 6 Beta 7 now.



Your problem is that you are trying to load images inside the cellForRow function. By the time the image is loaded, your CollectionView is showing a different cell. One of the correct ways to do this is to load the images inside viewDidLoad into an array, and then load from that array inside your cellForRow.



All Articles