考虑简化的示例:
struct ContainerView<Content: View>: View {
var header: String
var content: Content
init(header: String, @ViewBuilder content: () -> Content) {
self.header = header
self.content = content()
}
var body: some View {
VStack(spacing: 16) {
Text(header)
content
}
}
}
/// Usage
ContainerView(header: "Header") {
if showFirst {
Text("First").border(Color.yellow)
}
if showSecond {
Text("Second").border(Color.green)
}
}
我希望当第一个和第二个项目都没有显示时整个容器(包括标题)消失。现实中这样的条件项可以有很多,条件很复杂,我真的不想重复。一些检查可以包装到子视图类型中。
有没有办法使用 SwiftUI API 检查
content
是否实际上为空?
Group(subviews:)
获取所有子视图的集合,然后您可以检查它是否为空。
struct ContainerView<Content: View>: View {
var header: String
var content: Content
init(header: String, @ViewBuilder content: () -> Content) {
self.header = header
self.content = content()
}
var body: some View {
Group(subviews: content) { subviews in
if !subviews.isEmpty {
VStack(spacing: 16) {
Text(header)
content
}
}
}
}
}
iOS 18之前,您可以使用
_VariadicView
API。想法是一样的
var body: some View {
_VariadicView.Tree(
MultiViewRoot { subviews in
if !subviews.isEmpty {
VStack(spacing: 16) {
Text(header)
content
}
}
}
) { content }
}
private struct MultiViewRoot<V: View>: _VariadicView_MultiViewRoot {
@ViewBuilder let views: (_VariadicView.Children) -> V
func body(children: _VariadicView.Children) -> some View {
views(children)
}
}