🔰flexible column
SwiftUI ⟩ Layout ⟩ Grids ⟩ flexible column
雖然本範例的兩個欄位都是 flexible columen 有且最小寬度 minimum 屬性分別為 50, 120:
let columns = [
GridItem(.flexible(minimum: 50)), // ⭐ flexible
GridItem(.flexible(minimum: 120)) // ⭐ flexible
]
但真正跑出來的欄位寬度,卻超乎我們的想像。



⬆️ 需要: 👔 VGridForEach
struct ContentView: View {
let columns = [
GridItem(.flexible(minimum: 50)), // ⭐ flexible
GridItem(.flexible(minimum: 120)) // ⭐ flexible
]
var body: some View {
grid(columns)
}
}
extension ContentView {
/// a grid of swatches
func grid(_ columns: [GridItem]) -> some View {
// 👔 VGridForEach
VGridForEach(0..<6, columns: columns){
numberSwatch($0)
}
.frame(width: 200) // grid width = scroll view width ⭐
.border(Color.yellow) // scroll view border (yellow)
.padding()
.border(Color.blue) // padding border (blue)
.frame(height: 300)
}
/// a color swatch with a number on it
@ViewBuilder func numberSwatch(_ i: Int) -> some View {
let color: Color = i % 2 == 0 ? .green : .pink
color
.opacity(0.5)
.frame(height: 40)
.overlay(Text("\(i)").font(.title))
}
}
// initial values
r = 200 // remaining width (intial = grid width)
n = 2 // # of remaining cols
// r -= (fixed widths) + (spacing between cols)
r -= 8 // 192
// 1st col width
w1 = clamp(r/n) // 192/2 = 96
= 96 // clamped to [50, .inf)
// update r, n
r -= w1 // 192 - 96 = 96
n -= 1 // 1
// 2nd col width
w2 = clamp(r/n) // 96/1 = 96
= 120 // clamped to [120, .inf) ⭐
// overall width
W = 96 + 8 + 120
= 224 // larger than original (200) ⭐
// frame stretched out 12 pts both sides
// ----------------------------
// 2nd (rendering) pass
// ----------------------------
r = W // 224: start with overall width
n = 2 // # of remaining cols
// r -= (fixed widths) + (spacing between cols)
r -= 8 // 216
// 1st col width
w1 = clamp(r/n) // 216/2 = 108
= 108 // clamped to [50, .inf)
// update r, n
r -= w1 // 108
n -= 1 // 1
// 2nd col width
w2 = clamp(r/n) // 108/1 = 108
= 120 // clamped to [120, .inf)
// overall width
W = 108 + 8 + 120 // final layout ⭐
= 236 // grid appears out of center by 6 pts ⭐
Last updated
Was this helpful?