SwiftUI #21:组
发布: (2026年1月8日 GMT+8 06:19)
1 min read
原文: Dev.to
Source: Dev.to
什么是 Group?
Group 将多个视图组合在一起,以避免 Stack(最大 10 个子视图)的子视图限制,并且可以一次性对多个视图应用样式。
在 SwiftUI 中使用 Group
组合视图并应用样式
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)
}
}
}
在没有 @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)
}
}