# flexible column

[SwiftUI](../../../..) ⟩ [Layout](../..) ⟩ [Grids](..) ⟩ flexible column

{% tabs %}
{% tab title="💈範例" %}
{% hint style="warning" %}
&#x20;雖然本範例的兩個欄位都是 <mark style="color:red;">**flexible columen**</mark> 有且最小寬度 <mark style="color:purple;">**minimum**</mark> 屬性分別為 <mark style="color:red;">**50, 120**</mark>：

```swift
let columns = [
    GridItem(.flexible(minimum: 50)),    // ⭐ flexible
    GridItem(.flexible(minimum: 120))    // ⭐ flexible
]
```

但真正跑出來的欄位寬度，卻超乎我們的想像。
{% endhint %}

![final layout](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M5-JmwCZMKh_d7RfBaN%2Fuploads%2FMQWeGi2b2zks98uZWj6T%2Fflexibles.png?alt=media\&token=966ccef3-3d8d-4ff9-824e-0f941902c470) ![2 passes](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M5-JmwCZMKh_d7RfBaN%2Fuploads%2FwUESV3ewt0s7a1jLTQoX%2Fgrid%20layout%20algorithm.jpg?alt=media\&token=7fa00b6d-7744-4128-9dbb-1370fcd0bef0) ![screenshot](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M5-JmwCZMKh_d7RfBaN%2Fuploads%2FXyXAZUZOTgp6KIEQey3i%2Fflex%20cols.png?alt=media\&token=420ed1f2-0d9c-4893-894b-d40c1eea3e6a)

⬆️ 需要： 👔 [VGridForEach](../vgridforeach)

```swift
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))
    }
}
```

{% hint style="info" %}
欄位寬度的計算方式：👉 [layout-algorithm](../layout-algorithm "mention")
{% endhint %}

```swift
// 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 ⭐
```
{% endtab %}

{% tab title="📘 手冊" %}
* SwiftUI ⟩ Layout ⟩ [LazyVGrid](https://developer.apple.com/documentation/swiftui/lazyvgrid) ⟩ [.init(columns:alignment: ...)](https://developer.apple.com/documentation/swiftui/lazyvgrid/init\(columns:alignment:spacing:pinnedviews:content:\))
{% endtab %}

{% tab title="📗 參考" %}
* [x] objc ⟩ [SwiftUI’s Grid Views](https://www.objc.io/blog/2020/11/23/grid-layout/) ⭐️⭐️ - how **flexible**/**adaptive** columns behave. (💈例一)
{% endtab %}

{% tab title="👥 相關" %}
* [layout-algorithm](../layout-algorithm "mention")
* [adaptive-column](adaptive-column "mention")
{% endtab %}
{% endtabs %}
