The Idea of Reuse
A table with 10,000 rows does not create 10,000 views. It creates only enough cells to fill the screen and reuses them as you scroll. That is why cells are "dequeued".
A Basic Table
swift
class FruitsViewController: UITableViewController {
private let fruits = ["Apple", "Banana", "Cherry", "Mango"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Fruits"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fruits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = fruits[indexPath.row]
content.image = UIImage(systemName: "leaf")
cell.contentConfiguration = content
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("Selected \(fruits[indexPath.row])")
}
}
| Method | Question it answers |
numberOfRowsInSection | How many rows? |
cellForRowAt | What does row N look like? |
didSelectRowAt | What happens on tap? |
numberOfSections | How many groups? |
Modern Way: Diffable Data Source
A diffable data source stores a snapshot of your data. When you apply a new snapshot, UIKit computes the changes and animates them for you. This avoids the infamous crash "number of rows does not match".
swift
struct Item: Hashable {
let id = UUID()
let title: String
}
class ListViewController: UIViewController {
enum Section { case main }
private var tableView = UITableView()
private var dataSource: UITableViewDiffableDataSource<Section, Item>!
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(tableView)
dataSource = UITableViewDiffableDataSource(tableView: tableView) { tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ??
UITableViewCell(style: .default, reuseIdentifier: "cell")
var content = cell.defaultContentConfiguration()
content.text = item.title
cell.contentConfiguration = content
return cell
}
apply([Item(title: "One"), Item(title: "Two"), Item(title: "Three")])
}
func apply(_ items: [Item], animated: Bool = true) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.main])
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: animated)
}
}
Swipe to Delete
swift
override func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, done in
// remove the item from your data, then apply a new snapshot
done(true)
}
return UISwipeActionsConfiguration(actions: [delete])
}
UICollectionView
A collection view arranges items in grids and custom layouts. The modern compositional layout builds layouts from items, groups and sections.
swift
func makeLayout() -> UICollectionViewLayout {
let item = NSCollectionLayoutItem(
layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)))
item.contentInsets = .init(top: 4, leading: 4, bottom: 4, trailing: 4)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(120)),
subitems: [item])
return UICollectionViewCompositionalLayout(section: NSCollectionLayoutSection(group: group))
}
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
Compare: In SwiftUI the same screen is just List(items) { Text($0.title) }. This difference is why SwiftUI is faster to write, and why understanding UIKit helps you appreciate what SwiftUI does for you.
Conclusion
UITableView displays reusable cells. Use diffable data sources and cell content configurations for safe, animated updates.
Quick Summary: Dequeue reusable cells, supply data through a data source, and prefer diffable snapshots. UICollectionView adds grids with compositional layout.