The Util Designer
SwiftUI LazyVGrid 的使用
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-21
LazyVGrid 和 LazyHGrid 都是一種容器元件Container View,它們的作用是把其子元件以格子化來排列,這篇主要是講講LazyVGrid的簡單使用。
1. 在創建LazyVGrid時,首先要指定多少個column,每個column的寬度,下面寬度指定了80.0,並顯示21個Text。
import SwiftUI

struct GridExample : View {
    var body: some View {
        let width = 80.0
        let columns = [
            GridItem(.fixed(width)),
            GridItem(.fixed(width)),
            GridItem(.fixed(width))
        ]
        LazyVGrid(columns: columns) {
            ForEach(0..<21) { i in
                Text("Item \(i)")
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .background(.gray)
                    .padding(.bottom, 5)
            }
        }
    }
}
2. 我們試試把21個子元件加到100個元件,看看會怎麼樣。
import SwiftUI

struct GridExample : View {
    var body: some View {
        let width = 80.0
        let columns = [
            GridItem(.fixed(width)),
            GridItem(.fixed(width)),
            GridItem(.fixed(width))
        ]
        LazyVGrid(columns: columns) {
            ForEach(0..<100) { i in
                Text("Item \(i)")
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .background(.gray)
                    .padding(.bottom, 5)
            }
        }
    }
}
3. 從上面例子,太多子元件,會超出整個屏幕,可以結合ScrollView一起,就可以拖動。
import SwiftUI

struct GridExample : View {
    var body: some View {
        let width = 80.0
        let columns = [
            GridItem(.fixed(width)),
            GridItem(.fixed(width)),
            GridItem(.fixed(width))
        ]
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(0..<100) { i in
                    Text("Item \(i)")
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(.gray)
                        .padding(.bottom, 5)
                }
            }
        }
    }
}