在 LazyVGrid 中将最后一行居中

问题描述

LazyVGrid 中,我显示来自服务器的数据(这里我以字母表为例),我的目标是在中心显示最后一行而不是 leading如果最后一行包含少于 3 个项目。可行吗?

目前,它看起来像这样:

enter image description here

struct ContentView: View {
   let alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    let preference = [
            GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())
        ]
    var body: some View {
    ScrollView {
        LazyVGrid(columns: preference) {
        ForEach(alphabet,id: \.self) { value in
            ZStack {
                Rectangle()
                    .frame(width: 120,height: 120)
                    .foregroundColor(Color(UIColor.systemIndigo))
                    .cornerRadius(16)
                Text(value.description)
                    .foregroundColor(.white)
                    .font(.title)
                    }
                }
            }
        }
    }
}

目标:

enter image description here

解决方法

延迟加载每个单元格

struct ContentView: View {
    let alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    let preference = [
        GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())
    ]
    var body: some View {
        ScrollView {
            LazyVGrid(columns: preference) {
                ForEach(alphabet.dropLast(alphabet.count % 3),id: \.self) { value in
                    Cell(value: value)
                }
            }
            
            LazyHStack {
                ForEach(alphabet.suffix(alphabet.count % 3),id: \.self) { value in
                    Cell(value: value)
                }
            }
        }
    }
}

提取您的 Cell 视图以实现可重用性

struct Cell: View {
    let value: String
    var body: some View {
        print(value)
       return ZStack {
            Rectangle()
                .frame(width: 120,height: 120)
                .foregroundColor(Color(UIColor.systemIndigo))
                .cornerRadius(16)
            Text(value)
                .foregroundColor(.white)
                .font(.title)
        }
    }
}