DevPrep

All topics › SwiftUI

How do you write a custom container with the Layout protocol?

Senior PRO

The gist

The Layout protocol (iOS 16) exposes the same mechanism HStack and VStack are built on. A container implements two methods: sizeThatFits(proposal:subviews:cache:) — what size I take for a given proposal, and placeSubviews(in:proposal:subviews:cache:) — where to put each child. Children are available as LayoutSubview proxies: you can ask them for a size for any proposal and call place(at:anchor:proposal:). The container cannot see their body or type — only sizes and layout values.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store