SwiftUI #21: Groups
Source: Dev.to
¿Qué es un Group?
Un Group agrupa varias vistas juntas para evitar el límite de sub‑vistas que tiene un Stack (máximo 10) y permite aplicar estilos a varias vistas al mismo tiempo.
Uso de Group en SwiftUI
Agrupar vistas y aplicar estilos
struct ContentView: View {
var body: some View {
VStack {
Group {
Text("Hola mundo 1")
Text("Hola mundo 2")
}
.foregroundStyle(.red)
Group {
Text("Hola mundo 3")
Text("Hola mundo 4")
}
.foregroundStyle(.blue)
.font(.title)
}
}
}
Condiciones dentro de una función sin @ViewBuilder
struct ContentView: View {
let opcion1 = false
func makeView(flag: Bool) -> some View {
Group {
if flag {
Text("Hola")
} else {
// ❌ error si no se envuelve en Group
Image(systemName: "star")
}
}
}
var body: some View {
makeView(flag: opcion1)
}
}