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)
    }
}
Back to Blog

相关文章

阅读更多 »

SwiftUI #20: 优先级

介绍 在 SwiftUI 中,Stack 会在其视图之间等距划分空间。如果视图放不下,它会为 Image 分配固定大小并进行缩减……

2026年如何成为 iOS 开发者

引言 在本文中,我将详细说明在2026年成为 iOS 开发者需要做些什么。本文面向两个群体:绝对初学者——那些没有…