如何解决在 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)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。