Hamza
Hamza

Reputation: 251

Show Array of images in Collection View Cell

I'm selecting multiple images from gallery and putting all the selected images in an array. I want to show these images that are in an array in my collection view. I have a collection view in which in a cell I have created an imageView. Now I'm trying to pass my array of images to the image view in the cell. But when I hit done button it only show one image in collection view cell. I have used break points to check my loop the loop is working fine but it is showing only one image. How can I show all the images in an array? My code is this:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = uploadDocCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UploadDocsImagesCollectionViewCell

    for i in 0..<imagesArray.count{
        cell.imageView.image = imagesArray[i]
    }

    return cell
}

Upvotes: 0

Views: 5816

Answers (2)

mag_zbc
mag_zbc

Reputation: 6982

You can't show several images in one ImageView. You are iterating through your images and assigning them to a single image view. That way each image replaces the previous one, so the image you see is the last one in the array.

What you need to do is to have as many cells as you have images, and show one image in each.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imagesArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = uploadDocCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UploadDocsImagesCollectionViewCell

    cell.imageView.image = imagesArray[indexPath.item]

    return cell
}

Upvotes: 7

Sergey Fedorov
Sergey Fedorov

Reputation: 219

You should return in number of items number of images, and set image in cell using indexPath row index as index of image from images array.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imagesArray.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UploadDocsImagesCollectionViewCell


        cell.imageView.image = imagesArray[indexPath.row]


    return cell
}

Upvotes: 1

Related Questions