How do you build a custom SwiftUI Layout?
SwiftUI's Layout protocol for bespoke arrangements.
conform to Layout, implement sizeThatFits to report the container size for a proposal, and placeSubviews to position each subview using its measured size.
WHAT THIS TESTS This checks whether you know the modern, first-class way to create arbitrary layouts in SwiftUI rather than hacking with GeometryReader and manual offsets. It tests understanding of the two-phase measure-then-place model that all SwiftUI layout follows.
A GOOD ANSWER COVERS You declare a struct conforming to the Layout protocol and use it like any built-in container, wrapping child views. The protocol requires two methods. sizeThatFits receives a ProposedViewSize, a collection of Subviews proxies, and an inout cache, and returns the size your container wants to occupy; you typically measure each subview by asking it for its sizeThatFits given a proposal, then compute the bounding size of your arrangement. placeSubviews receives the final CGRect bounds the parent assigned, the same proposal, the subviews, and the cache, and is where you call subview.place(at:anchor:proposal:) for each child, computing positions from your geometry, for instance angles around a circle for a radial layout. The two phases mirror SwiftUI's negotiation: the parent proposes a size, the layout reports what it needs, then placement happens within the granted bounds.
COMMON WRONG ANSWERS Suggesting GeometryReader plus absolute offsets, which breaks sizing and composition. Wrapping a UIKit view via UIViewRepresentable when a native solution exists. Confusing the order, trying to place before measuring.
LIKELY FOLLOW-UPS What is the role of the cache parameter? How do you read a subview's ideal size? How does layoutProperties or alignment guides fit in? When is a custom Layout overkill versus an HStack with spacers?
ONE CONCRETE EXAMPLE A RadialLayout arranges N icons evenly on a circle. In sizeThatFits it returns the proposal's size or a square fitting the radius. In placeSubviews it computes, for index i, an angle of i times two pi over count, then places each subview at center plus radius times cos and sin of that angle, using an anchor of center, producing a clock-face arrangement that resizes cleanly with the container.
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.