📦GridItem
SwiftUI ⟩ Layout ⟩ LazyGrids ⟩
The spacing of the last GridItem is ignored.
- adaptive column - 說明 adaptive column 如何計算欄位數量與寬度。 

struct ContentView: View {
    
    // 3 columns
    let threeColumns = [
    
        // first col
        GridItem(                   // controls: size, spacing, alignment
            .fixed(60),             // ⭐️ column width (enum GridItem.Size)
            spacing  : 10,          // ⭐️ space to next COLUMN
            alignment: .topTrailing // ⭐️ alignment in a CELL
        ),
        
        // second col
        GridItem(.fixed(120), spacing: 30, alignment: .center),
        
        // ⭐️ last column's `spacing` is ignored
        GridItem(.fixed(100), spacing: 10, alignment: .bottomTrailing),
    ]
    
    var body: some View {
        // vertical scroll view (by default)
        ScrollView {
            // ⭐️ VERTICAL columns
            // - cells flow HORIZONTALLY
            LazyVGrid(
                columns: threeColumns, // ⭐️ columns setting
                alignment: .center,    // ⭐️ for the cells as a whole
                spacing: 10            // ⭐️ space between ROWS
            ) {
                ForEach(0..<100) { i in
                    VStack {
                        switch i {
                        case 3: rect(.pink)
                        case 4: rect(.green).frame(height: 50)
                        case 5: rect(.blue).frame(width: 60, height: 30)
                        case 6: rect(.yellow).frame(width: 80)
                        default: rect(.gray4).frame(height: 30)
                        }
                    }.overlay(Text("\(i)"))
                }
            }
            .border(Color.orange)    // grid border
            .frame(width: 500)
            .padding(20)
        }
        .frame(height: 200)
        .border(Color.blue)           hi// scroll view border
    }
}
extension ContentView {
    func rect(_ color: Color) -> some View {
        Rectangle().fill(color)
    }
}⬆️ 需要: Repeatable
// ⭐️ GridItem + 🅿️ Repeatable
extension GridItem: Repeatable {}
let columns = GridItem(.flexible()) * 2問:「紅色」與「黃色」色塊 frame 沒有指定 height 卻縮到最小高度❓
Last updated
Was this helpful?