Proper Way to Iterate and Load Images from Array i

2020-07-27 03:27发布

问题:

I'm working on an app in Swift using XCode 6 and iOS 8. This app contains a collection view that I'd like to load an array of images into.

When I'm using just one image I can repeat it as many times as I'd like, but when iterating through the array only the last image is repeated vs the unique images appearing in the collection view.

My array is defined as this inside my class:

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")!
]

Next I have the following to iterate through the array and display the images:

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
}

This compiles and displays but is only displaying browntrout200.png. What am I missing to display all the images?

回答1:

What is happening is for ever collection view cell, you are iterating through your array and setting the image of the cell to every image in your array. The last image in your array is "browntrout200.png" and that is the only one you see. You need to use the indexPath to get a single image in your array.

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
}

Also, make sure you have the other UICollectionViewDataSource method set tor return the number of items in your listOfImages array.

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


标签: ios swift