ViewBuilder y contenedores genéricos
Acepte contenido arbitrario con @ViewBuilder.
ViewBuilder y contenedores genéricos 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.
Containers That Hold Anything
VStack and List accept whatever views you nest inside them. You can build your own container that holds arbitrary content too. 📦
What @ViewBuilder Does
The @ViewBuilder attribute lets a closure list several views without commas or arrays. It is the magic behind stacks.
VStack {
Text("One")
Text("Two")
}Accept content as a Closure
Make your container take a content closure marked @ViewBuilder. Callers then pass views just like they do for VStack.
struct Card<Content: View>: View {
@ViewBuilder var content: Content
}Generic over Content
The container is generic over its content type. That single struct can wrap a Text, an image, or a whole layout.
Render the Content
In your body, place the stored content inside whatever wrapper you want, like padding and a background.
var body: some View {
content.padding().background(.gray)
}Use Your Container
Call it with a trailing closure and nest any views inside. Your custom wrapper now feels just like a built-in one.
Card {
Text("Title")
Text("Body")
}Builder on Functions Too
Mark a helper function with @ViewBuilder to return different views from branches without wrapping them in a type.
@ViewBuilder
func footer(show: Bool) -> some View {
if show { Text("More") } else { EmptyView() }
}Conditionals in Builders
Inside a builder you can use if and switch freely. SwiftUI assembles the chosen branch into the final view tree.
Multiple Content Slots
A container can take more than one builder, like a header and a footer. Each slot is its own @ViewBuilder closure.
struct Panel<H: View, B: View>: View {
@ViewBuilder var header: H
@ViewBuilder var body2: B
}Reusable Layout Shells
Generic containers capture a layout shell once, like a bordered card, and let every screen fill it with unique content.
Type-Safe and Flexible
Because content is generic, the compiler still checks every view. You get flexibility without losing type safety.
Quick Check
Quick check on generic containers.
Recap: Build Flexible Containers
Combine @ViewBuilder with a generic content type to make containers that wrap any views. Reusable shells, full type safety. 🧠
Preguntas frecuentes
¿La lección «ViewBuilder y contenedores genéricos» es gratis?
Sí — el texto completo de «ViewBuilder y contenedores genéricos» 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 «ViewBuilder y contenedores genéricos»?
Acepte contenido arbitrario con @ViewBuilder. 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 «ViewBuilder y contenedores genéricos»?
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
- Extraer vistas reutilizables
- ViewModifiers personalizados
- ButtonStyle y LabelStyle
- ViewBuilder y contenedores genéricos