SwiftUI 容器參考
堆疊、網格、大綱與滾動增強。iOS 14 到 iOS 26。
來源:WWDC 2020-10031, 2022-10056, 2023-10148, 2024-10144, 2025-256
快速決策
| 使用案例 | 容器 | iOS |
|---|---|---|
| 固定視圖垂直/水平 | VStack / HStack | 13+ |
| 重疊視圖 | ZStack | 13+ |
| 大型可滾動列表 | LazyVStack / LazyHStack | 14+ |
| 多欄網格 | LazyVGrid | 14+ |
| 多列網格 (水平) | LazyHGrid | 14+ |
| 靜態網格,精確對齊 | Grid | 16+ |
| 階層式資料 (樹狀) | List 搭配 children: | 14+ |
| 自訂階層 | OutlineGroup | 14+ |
| 顯示/隱藏內容 | DisclosureGroup | 14+ |
第一部分:堆疊
VStack, HStack, ZStack
VStack(alignment: .leading, spacing: 12) {
Text("標題")
Text("副標題")
}
HStack(alignment: .top, spacing: 8) {
Image(systemName: "star")
Text("評分")
}
ZStack(alignment: .bottomTrailing) {
Image("photo")
Badge()
}
ZStack 對齊方式:.center (預設), .top, .bottom, .leading, .trailing, .topLeading, .topTrailing, .bottomLeading, .bottomTrailing
Spacer
HStack {
Text("左邊")
Spacer()
Text("右邊")
}
Spacer(minLength: 20) // 最小尺寸
LazyVStack, LazyHStack (iOS 14+)
僅在可見時渲染子視圖。請在 ScrollView 內使用。
ScrollView {
LazyVStack(spacing: 0) {
ForEach(items) { item in
ItemRow(item: item)
}
}
}
固定區域標題 (Pinned Section Headers)
ScrollView {
LazyVStack(pinnedViews: [.sectionHeaders]) {
ForEach(sections) { section in
Section(header: SectionHeader(section)) {
ForEach(section.items) { item in
ItemRow(item: item)
}
}
}
}
}
第二部分:網格
Grid (iOS 16+)
非懶加載網格,精確對齊。一次載入所有視圖。
Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10) {
GridRow {
Text("姓名")
TextField("輸入姓名", text: $name)
}
GridRow {
Text("電子郵件")
TextField("輸入電子郵件", text: $email)
}
}
修飾符:
gridCellColumns(_:)— 跨多欄gridColumnAlignment(_:)— 覆蓋欄對齊
Grid {
GridRow {
Text(\