在 LazyVGrid 中将最后一行居中

Center the last row in a LazyVGrid

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

目前看起来是这样的:

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

目标:

延迟加载每个单元格

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

检查您是否在最后一行并应用翻译效果。如果一行有2条,按width / 4翻译。如果一行有3条,按width / 6翻译,依此类推

someView
.transformEffect(
    .init(
        translationX: isLastRow ? metrics.size.width / 4 : 0,
        y: 0
    )
)