1 minute read

Designing a Custom Collection View Layout with UIKit

UIKit’s collection view is excellent at presenting repeating data, but UICollectionViewFlowLayout follows a predictable grid pattern. When cards need different sizes, overlap, pinned headings, or placement driven by content priority, a bespoke layout gives exact control without rebuilding the scrolling machinery. The result can still retain accessibility, cell reuse, and animation behaviour that UIKit already provides.

A custom collection view layout in UIKit is useful when the arrangement itself carries meaning rather than merely spacing rows and columns. Imagine an Australian events app: a major festival card could occupy the leading position, while smaller cards represent nearby gigs. If a concert has high relevance, it may gain more space; if a venue is temporarily unavailable, the layout needs room for a clear status message instead of hiding it.

That example also exposes why hard-coded frames are a poor foundation. The same arrangement must survive Dynamic Type, portrait and landscape, and different iPhone and iPad widths. It should use Australian English, display prices in AUD, and make GST treatment explicit where relevant. Cities such as Sydney, Melbourne, and Canberra may need different content densities, but users should not have to learn separate rules for each screen.

Start with the layout contract

The first decision is whether the design truly needs a new layout. UICollectionViewFlowLayout supports grids, lists, grouping, headers, and many estimated-item-size behaviours. A custom UICollectionViewLayout is justified when you need non-uniform geometry, custom placement rules, overlapping elements, or a visual hierarchy that cannot be expressed reliably through existing layout options. Merely recreating a grid adds maintenance cost without improving the product.

Begin with a small model that describes each item independently of UIKit. Give every item an index path, a measured size, a position, and optional metadata such as priority or state. Keep geometry calculations in plain Swift structures or functions, then convert the result into UICollectionViewLayoutAttributes. This separation makes the hardest part—the placement policy—easy to reason about and test without constructing a view hierarchy.

The model should also define boundaries: how many sections exist, which cells participate, whether an item may occupy a special position, and how much content follows it. A useful contract states that the layout produces deterministic frames for a given content size and data snapshot. Determinism matters because repeated calls during scrolling, rotation, and invalidation must not yield different answers for the same item.

Build attributes from a deterministic model

During prepare(), read the collection view’s bounds, item count, and section information, then calculate the frames needed for the content. Store returned attributes in dictionaries keyed by index path or a stable identifier. layoutAttributesForElements(in:) should retrieve only attributes intersecting the requested rectangle; layoutAttributesForItem(at:) should provide a direct lookup. With these caches, scrolling asks the same questions without repeatedly scanning every item.

The approach resembles the boundary used by a Linux kernel audit module, which places a narrow interface between an application and a complex system underneath. UIKit is not a kernel, and the technical domains are unrelated, but the architectural lesson transfers: keep domain policy in a module, expose only the information the caller needs, and avoid leaking implementation details into unrelated code.

Frame coordinates belong to the collection view’s content space, not the visible screen. That distinction prevents attributes from shifting when the user scrolls. Use consistent edge insets and content padding, then verify how the first and last sections meet the content boundaries. If cells can overlap, assign explicit zIndex values rather than relying on array order, and ensure touch handling follows the visible stacking order.

Handle scrolling and invalidation

A custom layout must report its full scrollable area through collectionViewContentSize. An incorrect value can make the last card unreachable, produce blank space, or let the content bounce before it should. Calculate the union of occupied frames, add the intended bottom inset, and test with one section, many sections, and a final section containing only a supplementary view. These cases reveal mistakes that a sample with several equal cells may hide.

Bounds changes require careful invalidation. Returning true from shouldInvalidateLayout(forBoundsChange:) for every horizontal or vertical scroll event can trigger expensive recalculation, while returning false for genuine size changes leaves stale frames. Compare old and new sizes, invalidate when dimensions or relevant insets change, and use an invalidation context when only a portion of the layout must be recomputed. For rotation or split-view resizing, invalidate the affected context rather than rebuilding blindly.

Content-driven changes need the same treatment. If an item’s priority changes, its size changes, or a status badge appears, call invalidateLayout(with:) for that item. Dynamic Type can alter measured content, while safe-area changes can alter usable width. After invalidation, confirm that supplementary views, pinned elements, and cached frame dictionaries remain consistent. Logging invalidation reasons during development makes performance regressions easier to trace than sporadic frame jumps.

Add decoration and eligibility states

Supplementary views are useful for section headers, filters, instructional notes, and status strips. Their geometry belongs in the same model as cells, so a header must reserve space before the first item and a footer must appear after the final frame. Register and provide these views through the data source, and support layoutAttributesForIntersupplementaryView(ofKind:at:) in the layout. If you implement layoutAttributesForDecorationView(ofKind:at:), decoration should remain subordinate to interactive content.

Decoration is more than visual polish: it can clarify grouping and explain why a card differs from its neighbours. A small label might identify an event as “Tonight,” “Sold out,” or “18+”. Keep these states explicit in the item model and let the layout reserve enough room for Dynamic Type instead of drawing text over content. The same need to make rules visible appears in jackpot bet sizes, where eligibility must be understandable before a user commits.

Eligibility states also influence arrangement. An unavailable item may need a muted treatment, a different badge, or placement after eligible options, but its absence can make the collection look broken. Decide whether it stays in the same slot, moves into a separate section, or is filtered entirely. Whichever policy you choose, encode it in the placement model and test it with long localised labels, empty states, and conflicting combinations such as a sold-out event that is also a featured event.

Test the layout as a system

Start with unit tests for the placement model. Feed it fixed content sizes and assert exact frames, section boundaries, content height, and invalidation decisions. A synthetic dataset can include a wide image, a missing image, a long title, and an item with elevated priority. Because the model has no dependency on live views, these tests run quickly and identify whether an error comes from geometry policy or UIKit integration.

Add UI tests that launch the collection view, scroll through each section, rotate the device, and apply accessibility text sizes. Snapshot tests are especially useful for detecting unintended movement, clipped badges, and overlapping frames. Performance tests should measure scrolling while the layout is being recalculated; a layout that appears correct but rebuilds thousands of attributes on every frame will still feel slow. Instruments can reveal whether cache lookups, image measurement, or repeated size estimation dominates the work.

Finally, review the layout with people who use it rather than only the device you develop on. Check reading order against the visual hierarchy, Dynamic Type at accessibility sizes, VoiceOver labels, and contrast for muted states. For the Australian market, include realistic data: Sydney and Melbourne event formats, Canberra dates, Australian date conventions, and AUD prices with clear GST wording. That mix exposes assumptions that neat placeholder data often conceals.

The practical takeaway is to treat a custom collection view layout as a deterministic geometry engine with a UIKit adapter, not as a long sequence of view-frame adjustments. Model the rules, cache the resulting attributes, invalidate only what changed, and verify the arrangement under realistic constraints; the scrolling view then becomes a dependable surface for whatever hierarchy the content requires.

Updated: