🍎 Swift & iOS Intermediate

What is UICollectionView?

Answer

UICollectionView displays items in customizable layouts — grids, carousels, custom arrangements. It's more flexible than UITableView but requires a layout object. Basic setup: class PhotosViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var photos: [UIImage] = [] let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 2 layout.minimumLineSpacing = 2 return UICollectionView(frame: .zero, collectionViewLayout: layout) }() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell") } // Required: func collectionView(_ cv: UICollectionView, numberOfItemsInSection section: Int) -> Int { photos.count } func collectionView(_ cv: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = cv.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell cell.imageView.image = photos[indexPath.item] return cell } // Layout: func collectionView(_ cv: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = (cv.bounds.width - 4) / 3 return CGSize(width: width, height: width) } }. Modern Compositional Layout (iOS 13+): let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3), heightDimension: .fractionalHeight(1)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(1/3)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section). DiffableDataSource (iOS 13+): type-safe, animated updates without manual reloadData.