iOS Development
UICollectionView
Swift Programming
Mobile App Development
Image Display

How to Display first 9 images in UICollectionview?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want a UICollectionView to show only the first nine images, the cleanest fix is to limit the data source rather than hide extra cells in the layout. The collection view should believe it has at most nine items, and every data-source method should read from that same trimmed list.

Limit the Backing Data

Start with the full image collection, then derive a second array containing only the visible subset.

swift
1import UIKit
2
3final class ImageGridViewController: UIViewController {
4    @IBOutlet private weak var collectionView: UICollectionView!
5
6    private let allImageNames = [
7        "photo1", "photo2", "photo3", "photo4", "photo5",
8        "photo6", "photo7", "photo8", "photo9", "photo10"
9    ]
10
11    private let maxVisibleImages = 9
12    private var visibleImageNames: [String] = []
13
14    override func viewDidLoad() {
15        super.viewDidLoad()
16        visibleImageNames = Array(allImageNames.prefix(maxVisibleImages))
17        collectionView.dataSource = self
18    }
19}

This keeps the limit in one place and makes the rest of the implementation much easier to reason about.

Implement the Data Source Against the Trimmed Array

Once the visible subset exists, the collection view should use it consistently.

swift
1extension ImageGridViewController: UICollectionViewDataSource {
2    func collectionView(_ collectionView: UICollectionView,
3                        numberOfItemsInSection section: Int) -> Int {
4        return visibleImageNames.count
5    }
6
7    func collectionView(_ collectionView: UICollectionView,
8                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
9        let cell = collectionView.dequeueReusableCell(
10            withReuseIdentifier: "ImageCell",
11            for: indexPath
12        ) as! ImageCell
13
14        let imageName = visibleImageNames[indexPath.item]
15        cell.imageView.image = UIImage(named: imageName)
16        return cell
17    }
18}

If the source contains fewer than nine images, prefix(9) simply returns all available items, so the same code still works.

Keep the Cell Simple

A basic collection-view cell usually only needs an image view and a small cleanup step.

swift
1import UIKit
2
3final class ImageCell: UICollectionViewCell {
4    @IBOutlet weak var imageView: UIImageView!
5
6    override func prepareForReuse() {
7        super.prepareForReuse()
8        imageView.image = nil
9    }
10}

prepareForReuse() matters when images are loaded asynchronously or when old content might flash during scrolling.

Build the 3 by 3 Layout Separately

Limiting the item count does not automatically produce a 3 by 3 grid. That is a layout concern, so keep it separate from the data limit.

swift
1extension ImageGridViewController: UICollectionViewDelegateFlowLayout {
2    func collectionView(_ collectionView: UICollectionView,
3                        layout collectionViewLayout: UICollectionViewLayout,
4                        sizeForItemAt indexPath: IndexPath) -> CGSize {
5        let spacing: CGFloat = 8
6        let totalSpacing = spacing * 4
7        let width = (collectionView.bounds.width - totalSpacing) / 3
8        return CGSize(width: width, height: width)
9    }
10
11    func collectionView(_ collectionView: UICollectionView,
12                        layout collectionViewLayout: UICollectionViewLayout,
13                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
14        return 8
15    }
16
17    func collectionView(_ collectionView: UICollectionView,
18                        layout collectionViewLayout: UICollectionViewLayout,
19                        minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
20        return 8
21    }
22}

This keeps the responsibilities clear:

  • the data source decides which items exist
  • the layout decides how those items are arranged

The Same Pattern Works for Remote Images

If the images come from a network request or photo library fetch instead of bundled assets, the pattern stays the same. Load the full list, trim it, then reload the collection view.

swift
1func updateImages(_ imageNames: [String]) {
2    visibleImageNames = Array(imageNames.prefix(maxVisibleImages))
3    collectionView.reloadData()
4}

That is better than checking if indexPath.item < 9 inside cellForItemAt, because the collection view still sees a coherent dataset.

Common Pitfalls

The biggest mistake is returning nine from numberOfItemsInSection while still indexing into the untrimmed source array inconsistently. That works until the data and indexing rules drift apart.

Another common issue is trying to hide extra cells in layout code. The data source should define what exists; layout should only define presentation.

People also forget that the source may contain fewer than nine images. Using prefix(9) handles that safely without extra branching.

Finally, keep the nine-item limit separate from the 3 by 3 layout math. Those are related visually, but they solve different problems.

Summary

  • Limit the backing data to the first nine items before reloading the collection view.
  • Use the trimmed array consistently in both item-count and cell-configuration methods.
  • Keep the nine-item cap separate from layout sizing logic.
  • The same approach works for bundled, remote, or photo-library images.
  • A coherent data source is simpler and safer than hiding extra cells after the fact.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.