赞
踩
iOS 14 Swift2.0是有个LazyVGrid和LazyHGrid这里就不提了
iOS13的情况下是不能使用这两个的
所以只能自己去实现
代码如下:
首先先对集合类型进行一个扩展 进行查找
extension Collection {
func group(by size: Int) -> [[Element]]? {
// Inspired by: https://lodash.com/docs/4.17.4#chunk
guard size > 0, !isEmpty else { return nil }
var start = startIndex
var slices = [[Element]]()
while start != endIndex {
let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex
slices.append(Array(self[start..<end]))
start = end
}
return slices
}
}
struct MyGrid<Content: View, T: Hashable>: View {
private let columns: Int //行数
private var list: [[T]] = [] //你的数据源
private let content: (_ index: Int,_ element: T) -> Content
init(columns: Int, list: [T], @ViewBuilder content:@escaping (_ index: Int,_ element: T) -> Content) {
self.columns = columns
self.content = content
self.list = list.group(by: columns) ?? []
}
var body: some View {
VStack(alignment: .leading, spacing: 0.0) {
ForEach(0 ..< self.list.count, id: \.self) { i in
HStack {
ForEach(self.list[i].indices, id: \.self) { index in
self.content(i * columns + index , self.list[i][index])
.frame(width:(UIScreen.main.bounds.size.width ) / columns)
}
}
}
}
}
}
调用如下:
//columns 每行有几个 list数据源
MyGrid(columns: 2, list: appDataCache.goodsList) { index,goods in
//下面的这部分你可以理解成自定义的collectionViewCell
memberSelectBtn()
.padding(.top,20)
.padding(.leading,24)
.padding(.trailing,24)
.onTapGesture {
}
}.padding(.top,12)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。