我正在try 创建一个水平的UICollectionView,可以将部分单元格左对齐,另一部分右对齐.左右单元格之间应留有空格.是否可以使用UICollectionView和UICollectionViewFlowLayout?
我try 了这个版本的UICollectionViewFlowLayout,但它不能正常工作.我在试着理解如何动态计算偏移量.
class LeftRightAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
var offset: CGFloat = 30
fileprivate var layoutAttributes = [UICollectionViewLayoutAttributes]()
fileprivate var contentSize = CGSize.zero
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
var attributes = superAttributes
let centerX = collectionView!.contentOffset.x + collectionView!.bounds.width / 2.0
for attribute in attributes {
let distance = abs(attribute.center.x - centerX)
let offset = min(abs(distance), self.offset)
let factor = (self.offset - offset) / self.offset
let translation = factor * attribute.size.width / 2
attribute.center.x += distance < self.offset ? (attribute.center.x < centerX ? -translation : translation) : 0
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}