正确的方法将数组中的图像迭代并加载到Swift中的CollectionViewController中

plu*_*mwd 2 ios swift

我正在使用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")!
]
Run Code Online (Sandbox Code Playgroud)

接下来我有以下内容来遍历数组并显示图像:

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
}
Run Code Online (Sandbox Code Playgroud)

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

Mr *_*ley 6

正在发生的事情是永远的集合视图单元格,您正在迭代您的数组并将单元格的图像设置为数组中的每个图像.数组中的最后一个图像是"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
}
Run Code Online (Sandbox Code Playgroud)

此外,请确保您具有其他UICollectionViewDataSource方法设置,以返回listOfImages数组中的项目数.

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return listOfImages.count
}
Run Code Online (Sandbox Code Playgroud)