2015-09-04 39 views
2

我正在使用XCode 6和iOS 8在Swift上的应用程序。这个应用程序包含一个集合视图,我想要加载一个图像数组。正确的方式来迭代和加载图像从数组到Swift的CollectionViewController

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

我的阵列被定义为这个我的类中:

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

回答

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 
} 

此外,请确保您有其他UICollectionViewDataSource方法集TOR返回您listOfImages阵列项目的数量。

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