Referencia de Contenedores SwiftUI
Stacks, cuadrículas, esquemas jerárquicos y mejoras de scroll. iOS 14 hasta iOS 26.
Fuentes: WWDC 2020-10031, 2022-10056, 2023-10148, 2024-10144, 2025-256
Decisión rápida
| Caso de uso | Contenedor | iOS |
|---|---|---|
| Vistas fijas verticales/horizontales | VStack / HStack | 13+ |
| Vistas superpuestas | ZStack | 13+ |
| Lista grande desplazable | LazyVStack / LazyHStack | 14+ |
| Cuadrícula de varias columnas | LazyVGrid | 14+ |
| Cuadrícula de varias filas (horizontal) | LazyHGrid | 14+ |
| Cuadrícula estática, alineación precisa | Grid | 16+ |
| Datos jerárquicos (árbol) | List con children: | 14+ |
| Jerarquías personalizadas | OutlineGroup | 14+ |
| Mostrar/ocultar contenido | DisclosureGroup | 14+ |
Parte 1: Stacks
VStack, HStack, ZStack
VStack(alignment: .leading, spacing: 12) {
Text("Título")
Text("Subtítulo")
}
HStack(alignment: .top, spacing: 8) {
Image(systemName: "star")
Text("Calificación")
}
ZStack(alignment: .bottomTrailing) {
Image("foto")
Badge()
}
Alineaciones de ZStack: .center (predeterminado), .top, .bottom, .leading, .trailing, .topLeading, .topTrailing, .bottomLeading, .bottomTrailing
Spacer
HStack {
Text("Izquierda")
Spacer()
Text("Derecha")
}
Spacer(minLength: 20) // Tamaño mínimo
LazyVStack, LazyHStack (iOS 14+)
Renderiza hijos solo cuando son visibles. Úsalos dentro de ScrollView.
ScrollView {
LazyVStack(spacing: 0) {
ForEach(elementos) { elemento in
FilaElemento(elemento: elemento)
}
}
}
Encabezados de sección fijos
ScrollView {
LazyVStack(pinnedViews: [.sectionHeaders]) {
ForEach(secciones) { seccion in
Section(header: EncabezadoSeccion(seccion)) {
ForEach(seccion.elementos) { elemento in
FilaElemento(elemento: elemento)
}
}
}
}
}
Parte 2: Cuadrículas
Grid (iOS 16+)
Cuadrícula no perezosa con alineación precisa. Carga todas las vistas a la vez.
Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10) {
GridRow {
Text("Nombre")
TextField("Introduce nombre", text: $nombre)
}
GridRow {
Text("Correo")
TextField("Introduce correo", text: $correo)
}
}
Modificadores:
gridCellColumns(_:)— Abarcar varias columnasgridColumnAlignment(_:)— Anular alineación de columna
Grid {
GridRow {
Text("Encabezado").gridCellColumns(2)
}
GridRow {
Text("Izquierda")
Text("Derecha").gridColumnAlignment(.trailing)
}
}
LazyVGrid (iOS 14+)
Cuadrícula de desplazamiento vertical. Define columnas; las filas crecen sin límite.
let columnas = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
ScrollView {
LazyVGrid(columns: columnas, spacing: 16) {
ForEach(elementos) { elemento in
TarjetaElemento(elemento: elemento)
}
}
}
LazyHGrid (iOS 14+)
Cuadrícula de desplazamiento horizontal. Define filas; las columnas crecen sin límite.
let filas = [GridItem(.fixed(100)), GridItem(.fixed(100))]
ScrollView(.horizontal) {
LazyHGrid(rows: filas, spacing: 16) {
ForEach(elementos) { elemento in
TarjetaElemento(elemento: elemento)
}
}
}
GridItem.Size
| Tamaño | Comportamiento |
|---|---|
.fixed(CGFloat) | Ancho/alto exacto |
.flexible(minimum:maximum:) | Rellena el espacio por igual |
.adaptive(minimum:maximum:) | Crea tantos como quepan |
// Adaptativo: número de columnas responsivo
let columnas = [GridItem(.adaptive(minimum: 150))]
Parte 3: Esquemas jerárquicos
List con Datos Jerárquicos (iOS 14+)
struct ElementoArchivo: Identifiable {
let id = UUID()
var nombre: String
var hijos: [ElementoArchivo]? // nil = hoja
}
List(archivos, children: \.hijos) { archivo in
Label(archivo.nombre, systemImage: archivo.hijos != nil ? "folder" : "doc")
}
.listStyle(.sidebar)
OutlineGroup (iOS 14+)
Para diseños jerárquicos personalizados fuera de List.
List {
ForEach(lienzos) { lienzo in
Section(header: Text(lienzo.nombre)) {
OutlineGroup(lienzo.graficos, children: \.hijos) { grafico in
FilaGrafico(grafico: grafico)
}
}
}
}
DisclosureGroup (iOS 14+)
@State private var estaExpandido = false
DisclosureGroup("Opciones avanzadas", isExpanded: $estaExpandido) {
Toggle("Activar función", isOn: $funcion)
Slider(value: $intensidad)
}
Parte 4: Patrones comunes
Cuadrícula de fotos
let columnas = [GridItem(.adaptive(minimum: 100), spacing: 2)]
ScrollView {
LazyVGrid(columns: columnas, spacing: 2) {
ForEach(fotos) { foto in
AsyncImage(url: foto.urlMiniatura) { imagen in
imagen.resizable().aspectRatio(1, contentMode: .fill)
} placeholder: { Color.gray }
.aspectRatio(1, contentMode: .fill)
.clipped()
}
}
}
Carrusel horizontal
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: 16) {
ForEach(elementos) { elemento in
TarjetaCarrusel(elemento: elemento).frame(width: 280)
}
}
.padding(.horizontal)
}
Explorador de archivos
List(selection: $seleccion) {
OutlineGroup(elementosRaiz, children: \.hijos) { elemento in
Label {
Text(elemento.nombre)
} icon: {
Image(systemName: elemento.hijos != nil ? "folder.fill" : "doc.fill")
}
}
}
.listStyle(.sidebar)
Parte 5: Rendimiento
Cuándo usar Lazy
| Tamaño | ¿Desplazable? | Usar |
|---|---|---|
| 1-20 | No | VStack/HStack |
| 1-20 | Sí | VStack/HStack en ScrollView |
| 20-100 | Sí | LazyVStack/LazyHStack |
| 100+ | Sí | LazyVStack/LazyHStack o List |
| Cuadrícula <50 | No | Grid |
| Cuadrícula 50+ | Sí | LazyVGrid/LazyHGrid |
Almacena en caché los arreglos de GridItem — defínelos fuera del cuerpo:
struct VistaContenido: View {
let columnas = [GridItem(.adaptive(minimum: 150))] // ✅
var body: some View {
LazyVGrid(columns: columnas) { ... }
}
}
Rendimiento iOS 26
- Carga de listas 6 veces más rápida para 100k+ elementos
- Actualizaciones de listas 16 veces más rápidas
- Reducción de fotogramas caídos en desplazamiento
- ScrollViews anidados con stacks perezosos ahora difieren la carga correctamente:
ScrollView(.horizontal) {
LazyHStack {
ForEach(conjuntosFotos) { conjunto in
ScrollView(.vertical) {
LazyVStack {
ForEach(conjunto.fotos) { VistaFoto(foto: $0) }
}
}
}
}
}
Parte 6: Mejoras de scroll
containerRelativeFrame (iOS 17+)
Dimensiona las vistas en relación al contenedor de desplazamiento.
ScrollView(.horizontal) {
LazyHStack {
ForEach(tarjetas) { tarjeta in
VistaTarjeta(tarjeta: tarjeta)
.containerRelativeFrame(.horizontal, count: 3, span: 1, spacing: 16)
}
}
}
scrollTargetLayout (iOS 17+)
Habilita el ajuste (snapping).
ScrollView(.horizontal) {
LazyHStack {
ForEach(elementos) { TarjetaElemento(elemento: $0) }
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
scrollPosition (iOS 17+)
Rastrea el elemento visible más superior. Requiere .id() en cada elemento.
@State private var posicion: Elemento.ID?
ScrollView {
LazyVStack {
ForEach(elementos) { elemento in
FilaElemento(elemento: elemento).id(elemento.id)
}
}
}
.scrollPosition(id: $posicion)
scrollTransition (iOS 17+)
.scrollTransition { contenido, fase in
contenido
.opacity(1 - abs(fase.valor) * 0.5)
.scaleEffect(fase.esIdentidad ? 1.0 : 0.75)
}
onScrollGeometryChange (iOS 18+)
.onScrollGeometryChange(for: Bool.self) { geo in
geo.contentOffset.y < geo.contentInsets.top
} action: { _, estaArriba in
mostrarBotonAtras = !estaArriba
}
onScrollVisibilityChange (iOS 18+)
ReproductorVideo(jugador: jugador)
.onScrollVisibilityChange(threshold: 0.2) { visible in
visible ? jugador.play() : jugador.pause()
}
Recursos
WWDC: 2020-10031, 2022-10056, 2023-10148, 2024-10144, 2025-256
Docs: /swiftui/lazyvstack, /swiftui/lazyvgrid, /swiftui/lazyhgrid, /swiftui/grid, /swiftui/outlinegroup, /swiftui/disclosuregroup
Skills: axiom-swiftui-layout, axiom-swiftui-layout-ref, axiom-swiftui-nav, axiom-swiftui-26-ref