gpt4 book ai didi

ios - 在 Swift 中迭代并将图像从数组加载到 Collection View Controller 的正确方法

转载 作者:可可西里 更新时间:2023-11-01 00:23:40 24 4
gpt4 key购买 nike

我正在使用 XCode 6 和 iOS 8 在 Swift 中开发一个应用程序。这个应用程序包含一个 Collection View ,我想将图像数组加载到其中。

当我只使用一张图片时,我可以根据需要重复多次,但是当遍历数组时,只重复最后一张图片,而不是出现在 Collection View 中的唯一图片。

我的数组在我的类中定义为:

var listOfImages: [UIImage] = [
UIImage(named: "4x4200.png")!,
UIImage(named: "alligator200.png")!,
UIImage(named: "artificialfly200.png")!,
UIImage(named: "baitcasting200.png")!,
UIImage(named: "bassboat200.png")!,
UIImage(named: "bighornsheep200.png")!,
UIImage(named: "bison200.png")!,
UIImage(named: "blackbear200.png")!,
UIImage(named: "browntrout200.png")!
]

接下来,我使用以下代码遍历数组并显示图像:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell


// Configure the cell
for images in listOfImages{
cell.imageView.image = images
}

return cell
}

这会编译并显示,但只显示 browntrout200.png。我缺少什么来显示所有图像?

最佳答案

发生的是永远的 Collection View 单元格,您正在遍历数组并将单元格的图像设置为数组中的每个图像。数组中的最后一张图片是“browntrout200.png”,这是您看到的唯一一张图片。您需要使用 indexPath 来获取数组中的单个图像。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = listOfImages[indexPath.row]

return cell
}

此外,请确保将其他 UICollectionViewDataSource 方法设置为返回 listOfImages 数组中的项目数。

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

关于ios - 在 Swift 中迭代并将图像从数组加载到 Collection View Controller 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com