๐ฐflexible column
Last updated
Was this helpful?
Last updated
Was this helpful?
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))
}
}
ๆฌไฝๅฏฌๅบฆ็่จ็ฎๆนๅผ๏ผ๐ grid layout algorithm
// 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 โญ
SwiftUI โฉ Layout โฉ LazyVGrid โฉ .init(columns:alignment: ...)