常用的UICollectionViewFlowLayout
只有一个设置 cell 最小水平间距的属性minimumInteritemSpacing
,但是只设置最小间距有时并不能满足我们的需求,如:
我们期望的是 cell 与 cell 之间的间距是固定的,上图显然不满足要求。
这个时候可以通过对UICollectionViewFlowLayout
进行简单的扩展达到目的,方法是继承UICollectionViewFlowLayout
然后重写layoutAttributesForElements
方法:
class MaxCellSpacingLayout: UICollectionViewFlowLayout {
/// 最大cell水平间距
var maximumInteritemSpacing: CGFloat = 0.0
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
if attributes?.count == 0 {
return attributes
}
let firstCellOriginX = attributes?.first?.frame.origin.x
if let count = attributes?.count {
for i in 1..<count {
let currentLayoutAttributes = attributes![i]
let previousLayoutAttributes = attributes![i-1]
if currentLayoutAttributes.frame.origin.x == firstCellOriginX {
continue
}
let previousOriginMaxX = previousLayoutAttributes.frame.maxX
if currentLayoutAttributes.frame.origin.x - previousOriginMaxX > maximumInteritemSpacing {
var frame = currentLayoutAttributes.frame
frame.origin.x = previousOriginMaxX + maximumInteritemSpacing
currentLayoutAttributes.frame = frame
}
}
}
return attributes
}
}
使用:
layout.maximumInteritemSpacing = 20
网友评论