Skip to Content
Course content

232: Practice Exercise: Building a Custom Layout with the Layout Protocol

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a pattern with a lot of developers moving into advanced SwiftUI: they treat the Layout protocol as a "break glass in case of emergency" tool. Usually, the misconception is that any layout—no matter how complex—can be achieved if you just nest enough HStacks, VStacks, and ZStacks, perhaps throwing in some .offset() modifiers to nudge things into place.

Thinking Nested Stacks Can Handle Non-Linear Geometry

Here is why that mindset will eventually lead you into a wall of frustration. Imagine you want to build a radial menu where items are arranged in a perfect circle around a center point. If you try to do this with stacks, you're fighting the system. You'll end up calculating offsets manually for every single element based on sine and cosine, then you'll realize that when the screen size changes or the views have different content lengths, your "perfect circle" is now an oval of overlapping text. You're trying to force a linear coordinate system (rows and columns) to behave like a polar coordinate system.

// The "wrong" way: Fighting the framework
HStack {
    Text("Item 1").offset(x: -50, y: 20)
    Text("Item 2").offset(x: 0, y: -50)
    Text("Item 3").offset(x: 50, y: 20)
}
// This is brittle. It doesn't scale, and it doesn't actually 
// communicate the layout's intent to the SwiftUI engine.


Taking Control of the Proposal and Placement Cycle

When you use the Layout protocol, you stop guessing and start commanding. Instead of hoping the stack puts a view in the right place, you get to participate in the two-step negotiation that SwiftUI performs: Size Proposal and Placement.

First, the system calls sizeThatFits. This is where you tell SwiftUI, "Given this amount of space, here is how much I actually need to fit my children." I like to think of this as the "request" phase. You aren't placing views yet; you're just defining the boundary of your custom container.

Second, the system calls placeSubviews. This is the magic part. You get a SublayoutProxy that lets you ask each child view how big it wants to be, and then you provide a CGPoint for exactly where it should go. No more offsets or padding hacks—just raw coordinates.

Here is a concrete example of a RadialLayout. Notice how we calculate the center of the available space and use basic trigonometry to distribute the views. This is infinitely more robust than nested stacks because it recalculates dynamically based on the actual proposed size.

struct RadialLayout: Layout {
    var maxRadius: CGFloat = 100

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        // We want a square area that can fit our radius in all directions
        let side = maxRadius * 2
        return CGSize(width: side, height: side)
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let angleStep = (2 * Double.pi) / Double(subviews.count)

        for (index, subview) in subviews.enumerated() {
            let angle = angleStep * Double(index)
            
            // Calculate the position on the circumference of the circle
            let x = center.x + cos(angle) * maxRadius
            let y = center.y + sin(angle) * maxRadius
            
            subview.place(
                at: CGPoint(x: x, y: y), 
                anchor: .center, 
                proposal: .unspecified
            )
        }
    }
}


I'll give you a pro tip: always pay attention to the anchor parameter in the place method. By default, views are placed by their top-left corner. If you're building something symmetrical like a circle or a grid, setting the anchor to .center will save you from doing a lot of tedious subtraction of half-widths and half-heights.




📋 Practical Task

Exercise: Building a Concentric Ring Gallery

Instead of a single circle, your task is to create a custom layout called ConcentricLayout. This layout should distribute its subviews across multiple concentric rings. If there are 10 views, for example, the first 4 should be in an inner ring (radius 50) and the remaining 6 should be in an outer ring (radius 120).

Requirements:

  • Implement the Layout protocol.
  • Define a logic in placeSubviews that checks the index of the subview to determine which radius to use.
  • Ensure the sizeThatFits method returns a size large enough to encompass the outermost ring.
  • Use .center as the anchor for placing subviews to ensure they are perfectly centered on their calculated coordinates.
  • Test your layout by placing 12 different Circle() or Image() views inside it.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.