๐Ÿ”ฐ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))
    }
}

ๆฌ„ไฝๅฏฌๅบฆ็š„่จˆ็ฎ—ๆ–นๅผ๏ผš๐Ÿ‘‰ 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 โญ

Last updated