JamesG
JamesG

Reputation: 1601

Swift change UIImage in UICollectionViewCell from Array

I have an array:

 var categoryImages = ["image1","image2","image3","image4"]

and this is how I am trying to get the images to change:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
    myCell.backgroundColor = UIColor.blue

    let size = CGRect(x: 0, y: 0, width: 100, height: 100)

    var imageview: UIImageView = UIImageView(frame: size)

    let image: UIImage = UIImage(named: categoryImages[indexPath])
    imageview.image = image
    myCell.contentView.addSubview(imageview)
    return myCell
}

However, this line:

let image: UIImage = UIImage(named: categoryImages[indexPath])

throws this error:

Cannot subscript a value of type '[String]' with an index of type 'IndexPath'

Can someone help me: I would like images that are in the array to load into the UICollectionViewCells. Not as background images however, I would like them as images I can position etc..

Thanks in advance.

Upvotes: 0

Views: 380

Answers (2)

Zeb
Zeb

Reputation: 1725

You need to access the array of images using the row: indexPath.row.

Upvotes: 0

Olga Nesterenko
Olga Nesterenko

Reputation: 1334

try this:

let image: UIImage = UIImage(named: categoryImages[indexPath.row])

Your categoryImages is an array, so you need to get the elements from it by their indexes.

Upvotes: 3

Related Questions