O Protocolo de Layout
Implemente sizeThatFits e placeSubviews.
O Protocolo de Layout é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Beyond Stacks
When stacks and grids are not enough, the Layout protocol lets you write your own container that positions children exactly how you want. 🧩
Two Required Methods
Conform to Layout by implementing sizeThatFits and placeSubviews, the two steps every custom layout needs.
struct MyLayout: Layout {
func sizeThatFits(...) -> CGSize { ... }
func placeSubviews(...) { ... }
}Sizing Yourself
In sizeThatFits, you measure the children and return the total size your container wants to occupy.
func sizeThatFits(proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()) -> CGSize {
CGSize(width: 200, height: 100)
}The Proposal
The ProposedViewSize is the space the parent offers. You decide how to use or shrink within it.
let width = proposal.width ?? 0The Subviews Proxy
The subviews argument is a collection of proxies. Ask each one for its preferred size before placing it.
for view in subviews {
let size = view.sizeThatFits(.unspecified)
}Placing Children
In placeSubviews, you loop and call place on each subview with an exact point and an anchor.
func placeSubviews(in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()) {
}The place Call
Each place call sets the origin, the anchor point, and the size proposal for that one child.
view.place(at: point,
anchor: .topLeading,
proposal: .unspecified)Walk a Cursor
A simple layout keeps an x cursor, placing each child then advancing by its width plus spacing.
var x = bounds.minX
for view in subviews {
let s = view.sizeThatFits(.unspecified)
view.place(at: CGPoint(x: x, y: bounds.minY),
proposal: .unspecified)
x += s.width
}Using Your Layout
A Layout type is used just like a stack: wrap your views in it and they get arranged by your code.
MyLayout {
Text("One")
Text("Two")
}Optional Cache
The cache parameter lets you store expensive measurements between passes; use Void when you do not need it.
It Is Value-Based
Because a Layout is a struct, SwiftUI can re-run it cheaply, keeping custom containers fast and predictable. ⚡
Quick Check
Recall the two methods every Layout must implement.
Recap
You can now build a custom container with the Layout protocol by measuring in sizeThatFits and positioning in placeSubviews. 🎉
Perguntas Frequentes
A aula “O Protocolo de Layout” é grátis?
Sim — o texto completo de “O Protocolo de Layout” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.
O que vou aprender em “O Protocolo de Layout”?
Implemente sizeThatFits e placeSubviews. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar SwiftUI Academy?
Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “O Protocolo de Layout”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de SwiftUI Academy?
Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Fundamentos do GeometryReader
- Guias de Alinhamento Personalizadas
- O Protocolo de Layout
- Criando um Layout de Fluxo