p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #08fa95 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #4bd156 }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #ffffff }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #ffffff; min-height: 21.0px }
p.p5 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #00b1ff }
p.p6 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #ff4647 }
span.s1 { color: #de38a5 }
span.s2 { color: #ffffff }
span.s3 { }
span.s4 { font: 18.0px "PingFang SC" }
span.s5 { color: #00b1ff }
span.s6 { color: #8b87ff }
span.s7 { color: #08fa95 }
span.s8 { color: #4bd156 }
span.s9 { font: 18.0px "PingFang SC"; color: #4bd156 }
完整实现代码请点击: https://git.oschina.net/null_248_6948/WaterfallLayout.git
extension WaterfallLayout {
// prepare准备所有Cell的布局样式
override func prepare() {
super.prepare()
// 0.获取item的个数
let itemCount = collectionView!.numberOfItems(inSection: 0)
// 1.获取列数
let cols = dataSource?.numberOfColsInWaterfallLayout?(self) ?? 2
// 2.计算Item的宽度
let itemW = (collectionView!.bounds.width - self.sectionInset.left - self.sectionInset.right - self.minimumInteritemSpacing * CGFloat((cols - 1))) / CGFloat(cols)
// 3.计算所有的item的属性
for i in startIndex..<itemCount {
// 1.设置每一个Item位置相关的属性
let indexPath = IndexPath(item: i, section: 0)
// 2.根据位置创建Attributes属性
let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
// 3.随机一个高度
guard let height = dataSource?.waterfallLayout(self, indexPath: indexPath) else {
fatalError("请设置数据源,并且实现对应的数据源方法")
}
// 4.取出最小列的位置
var minH = colHeights.min()!
let index = colHeights.index(of: minH)!
minH = minH + height + minimumLineSpacing
colHeights[index] = minH
// 5.设置item的属性
attrs.frame = CGRect(x: self.sectionInset.left + (self.minimumInteritemSpacing + itemW) * CGFloat(index), y: minH - height - self.minimumLineSpacing, width: itemW, height: height)
attrsArray.append(attrs)
}
// 4.记录最大值
maxH = colHeights.max()!
// 5.给startIndex重新复制
startIndex = itemCount
}
}