Ios 在Swift中迭代并将图像从阵列加载到CollectionViewController的正确方法
我正在使用XCode 6和iOS 8在Swift中开发一个应用程序。此应用程序包含一个集合视图,我想将一组图像加载到其中 当我只使用一个图像时,我可以根据自己的喜好重复多次,但是当在数组中迭代时,只重复最后一个图像,而不是集合视图中显示的唯一图像 我的数组在我的类中定义为:Ios 在Swift中迭代并将图像从阵列加载到CollectionViewController的正确方法,ios,swift,Ios,Swift,我正在使用XCode 6和iOS 8在Swift中开发一个应用程序。此应用程序包含一个集合视图,我想将一组图像加载到其中 当我只使用一个图像时,我可以根据自己的喜好重复多次,但是当在数组中迭代时,只重复最后一个图像,而不是集合视图中显示的唯一图像 我的数组在我的类中定义为: var listOfImages: [UIImage] = [ UIImage(named: "4x4200.png")!, UIImage(named: "alligator200.png")!,
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。显示所有图像时我缺少了什么?正在发生的是“永久收集”视图单元格,您正在迭代数组,并将单元格的图像设置为数组中的每个图像。数组中的最后一个图像是“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
}