Layout Containers (佈局容器)
VStack (垂直排列)
- 垂直排列子視圖
alignment
leading : 靠左對齊
center : 置中對齊 (default)
trailing : 靠右對齊
spacing
VStack(alignment: .leading, spacing: 10) {
Text("A")
Text("B")
Text("C")
}
HStack (水平排列)
- 水平排列子視圖
alignment
top : 靠頂對齊
center : 置中對齊 (default)
bottom : 靠底對齊
spacing
HStack(alignment: .center, spacing: 10) {
Text("A")
Text("B")
Text("C")
}
ZStack (疊放)
ZStack(alignment: .leading) {
Text("ZStack1")
Text("ZStack2")
}
Lazy Containers (延遲容器)
- 當出現在畫面時才渲染元件
pinnedViews
- 將綁定一個 PinnedScrollableViews 元件作為渲染的依據
LazyVStack (垂直排列)
LazyVStack {
ForEach(0..<100) { Text("Item \($0)") }
}
LazyHStack (水平排列)
LazyHStack {
ForEach(0..<100) { Text("Item \($0)") }
}
LazyVGrid (垂直格狀佈局)
- 垂直格狀佈局
columns
- 傳入
[GridItem] 物件說明每一列的元件可佔寬度
fixed
flexible
- 彈性寬度
minimum : 最小寬度 (default 10)
maximum : 最大寬度 (default infinity)
adaptive
- 指定一個
flexible 尺寸,盡可能地以最小寬度填滿空間
let columns = [GridItem(.flexible()), GridItem(.flexible())]
LazyVGrid(columns: columns) {
ForEach(0..<10, id: \.self) { _ in
Text("LazyVGrid")
}
}
LazyHGrid (水平格狀佈局)
- 水平格狀佈局
rows
- 傳入
[GridItem] 物件說明每一行的元件可佔高度
fixed
flexible
- 彈性寬度
minimum : 最小寬度 (default 10)
maximum : 最大寬度 (default infinity)
adaptive
- 指定一個
flexible 尺寸,盡可能地以最小寬度填滿空間
let rows = [GridItem(.flexible()), GridItem(.flexible())]
LazyHGrid(rows: rows) {
ForEach(0..<10, id: \.self) { _ in
Text("LazyHGrid")
}
}
GeometryReader (幾何讀取器)
- 透過
GeometryProxy 獲得父視圖的尺寸資訊
GeometryReader { geometry in
Text("Width: \(geometry.size.width)")
}
Layout Protocol (自訂佈局)
- SwiftUI 4.0 (1OS 16.0+) 提供
Layout 協議
- 使用
Layout 協議需實現
sizeThatFits
placeSubviews
struct MyCustomLayout: Layout {
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
return CGSize(width: 100, height: 100)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
for subview in subviews {
subview.place(at: CGPoint(x: bounds.midX, y: bounds.midY), proposal: proposal)
}
}
}
MyCustomLayout {
Text("Custom Layout")
}