SwiftUI Academy · Lección

Crear un Flow Layout

Cree un layout envolvente de estilo etiquetas.

Lección 4 de 413 pasos

Crear un Flow Layout es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What Is a Flow?

A flow layout places items left to right and wraps to a new line when they run out of room, like word-wrapped text. 🏷️

Perfect for Tags

This wrapping behavior is exactly what you want for tag chips, hashtags, or filter pills of varying widths.

Start with Layout

Build it by conforming to the Layout protocol so you control wrapping yourself, since no stack wraps automatically.

struct FlowLayout: Layout {
    var spacing: CGFloat = 8
}

Measure Each Chip

In sizeThatFits, ask every subview for its size, then simulate placing them to find the total height needed.

let sizes = subviews.map {
    $0.sizeThatFits(.unspecified)
}

Track a Cursor

Keep an x and a y cursor. Move x rightward for each chip and reset when the next chip would overflow.

var x: CGFloat = 0
var y: CGFloat = 0

Detect Overflow

Before placing a chip, check if x plus its width exceeds the available width; if so, wrap to the next row.

if x + size.width > maxWidth {
    x = 0
    y += rowHeight + spacing
}

Advance the Row

After placing a chip, move x forward by its width plus spacing and grow rowHeight to the tallest chip seen.

x += size.width + spacing
rowHeight = max(rowHeight, size.height)

Place in the Second Pass

In placeSubviews, repeat the same wrapping math but call place at each computed point.

view.place(at: CGPoint(x: bounds.minX + x,
                       y: bounds.minY + y),
           proposal: .unspecified)

Return the Height

Your sizeThatFits should return the proposed width and the final y plus the last row height.

CGSize(width: maxWidth,
       height: y + rowHeight)

Drop It In

Now use it like any container: wrap your chips and the FlowLayout wraps them across as many lines as needed.

FlowLayout {
    ForEach(tags, id: \.self) { tag in
        TagChip(tag)
    }
}

Reusable Anywhere

Because it is a real Layout, your flow works with any views, adapts to width, and animates with the rest of SwiftUI. ✨

Quick Check

Recall what triggers a new row in a flow layout.

Recap

You built a wrapping FlowLayout with the Layout protocol, tracking a cursor to flow chips across rows automatically. 🎉

Gratis para empezar

Aprende Swift con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
30
Lecciones
120

Preguntas frecuentes

¿La lección «Crear un Flow Layout» es gratis?

Sí — el texto completo de «Crear un Flow Layout» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Crear un Flow Layout»?

Cree un layout envolvente de estilo etiquetas. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar SwiftUI Academy?

No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Crear un Flow Layout»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?

Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Fundamentos de GeometryReader
  2. Guías de alineación personalizadas
  3. El protocolo Layout
  4. Crear un Flow Layout
← Volver a SwiftUI Academy