正确的方法来迭代和从数组加载图像到Swift的CollectionViewController

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

当我只使用一个图像时,我可以多次重复,但是当遍历数组时,只有最后一个图像重复出现在集合视图中的唯一图像上。

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

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。 我错过了什么显示所有的图像?

发生什么事是永远的集合视图单元格,你遍历你的数组,并设置单元格的图像到数组中的每个图像。 你arrays中的最后一张图片是“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 }