tezvyn:

UICollectionView: Grids, Stacks, and Custom Layouts

AI-drafted, machine-checkedSource: developer.apple.comintermediate
UICollectionView: Grids, Stacks, and Custom Layouts

UICollectionView is a powerful tool for displaying items in customizable layouts, going far beyond a simple vertical list. Use it for photo galleries or App Store-style interfaces.

WHY IT EXISTS Simple lists (UITableView) are efficient but rigid. iOS needed a component that could manage and display collections of data in highly complex, non-linear, and dynamic arrangements, like grids, stacks, or even circular layouts, while still being highly performant.

THE MENTAL MODEL Think of UICollectionView not as a list, but as a managed canvas. You provide the data (items) and a set of rules (the layout object). The collection view then efficiently renders only the items currently visible, asking your layout object "Where does item 7 go? What size is it?"

HOW IT WORKS A UICollectionView works with three main components. First, the Data Source (UICollectionViewDataSource) provides the cells and supplementary views like headers. Second, the Delegate (UICollectionViewDelegate) handles user interactions like selection. Third, and most importantly, the Layout object (UICollectionViewLayout) tells the collection view the size, position, and attributes of every single item. The default is UICollectionViewFlowLayout for simple grids, but you can create custom layouts for anything imaginable.

WHEN TO USE IT Use UICollectionView for any data presentation that isn't a simple, single-column list. It's ideal for image galleries, magazine-style layouts, dashboards with widgets of different sizes, or the main interface of apps like the App Store or Photos. Its ability to dynamically change layouts makes it incredibly versatile.

WHEN NOT TO USE IT For a simple, single-column list of text-based items with uniform rows, UITableView is often simpler and more direct. Using UICollectionView for a basic settings screen, for example, would be overkill, adding unnecessary complexity compared to its simpler counterpart.

ONE CANONICAL EXAMPLE The iOS Photos app is a prime example. The "All Photos" view uses a UICollectionView with a UICollectionViewFlowLayout to display a tight grid of thumbnails. Tapping a photo can transition to a different layout within the same collection view to show a single, full-screen image that you can swipe through. The pinch-to-zoom gesture to change the grid density is also a classic collection view layout transition.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.