我试图创建一个水平的UICollectionView与可能性对齐单元格的左侧和其他部分的权利。左右单元格之间应该是空白。是否可以使用UICollectionView和UICollectionViewFlowLayout?
我尝试了这个版本的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
}
}
1条答案
按热度按时间8zzbczxx1#
请在layoutAttributesForElements函数中尝试以下代码: