Displaying Images in Cells

Displaying URLImageViews in dequeued cells is slightly different. Instead of passing the image URL into the initializer, you will manually load the image using the provided function below


Pass in the URL pointing to the image on your external server, etc. when the cell is dequeued

public func loadImageFrom(urlString: String)

Step 1/3


Define a URLImageView in your cell

class ImageCell: UICollectionViewCell {

    let imageView = URLImageView(delegate: nil, cacheLocation: .inMemory)
    
    // Set up subviews, constraints, etc.

    func configure(with imageURLString: String) {
        imageView.loadImageFrom(urlString: imageURLString)
    }
}

Step 2/3


Implement your UICollectionViewDataSource or UITableViewDataSource as usual

struct Image {
    let urlString: String
}

class ViewController: UIViewController, UICollectionViewDataSource {

    let images: [Image] = self.fetchData()

    func fetchData() -> [Image] {
        // Fetch images from external server, etc.

        // reloadData
    }

    numberOfItems....

    cellForItemAt....
}

// ...

Step 3/3


When the ImageCell is dequeued, load your image from the string for that indexPath

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as? ImageCell

    let imageURLString = images[indexPath.item].urlString

    cell?.configure(with: imageURLString)

    return cell ?? UICollectionViewCell()
}

// ...

Example


The images are fetched from external URLs, cached for reuse and displayed in the UICollectionViewCell.

As the UICollectionView is scrolled back up, the cached images are reused instead of re-fetching them.