[英]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' 无法用索引类型“ IndexPath”的下标“ [String]”的值
Can someone help me: I would like images that are in the array to load into the UICollectionViewCells. 有人可以帮我吗:我希望将数组中的图像加载到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. 您的categoryImages是一个数组,因此您需要通过它们的索引从中获取元素。
您需要使用以下行访问图像数组: indexPath.row
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.