简体   繁体   中英

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.

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.

您需要使用以下行访问图像数组: indexPath.row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM