The Layout Protocol Basics
Implement sizeThatFits and placeSubviews.
Why a Custom Layout?
SwiftUI ships with HStack, VStack, and ZStack, but sometimes you need arrangement logic they cannot express—radial menus, flow layouts, masonry grids.
The Layout protocol lets you write that logic while still composing with normal SwiftUI views.
The Layout Protocol
Layout requires two methods: sizeThatFits (how big am I?) and placeSubviews (where does each child go?).
You conform a value type and use it like any built-in stack.
struct MyLayout: Layout {
func sizeThatFits(proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()) -> CGSize { .zero }
func placeSubviews(in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()) { }
}All lessons in this course
- The Layout Protocol Basics
- Measuring Subviews
- Building a Flow Layout
- Layout Cache and Performance