我正在尝试实施UICollectionViewFlowLayout
或UICollectionViewLayout
- 任何方式都不会调用layoutAttributesForItem
。
我可以从其他人那里看到他们从layoutAttributesForItem
致电self.layoutAttributesForItem
。
赞this flowout示例:
我创建了一个你可以看到的Playground项目。总的来说,我只是想扩大中心视野。
答案 0 :(得分:4)
尝试通过Sub-Classing UICollectionViewFlowLayout
来使用它
let flowLayout = LeftAgignedFlowLayout()
flowLayout.minimumLineSpacing = 18
flowLayout.minimumInteritemSpacing = 8
flowLayout.scrollDirection = .vertical
self.collectionViewLayout = flowLayout
class LeftAgignedFlowLayout : UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let arr = super.layoutAttributesForElements(in: rect)!
return arr.map {
atts in
var atts = atts
if atts.representedElementCategory == .cell {
let ip = atts.indexPath
atts = self.layoutAttributesForItem(at:ip)!
}
return atts
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var atts = super.layoutAttributesForItem(at:indexPath)!
if indexPath.item == 0 {
return atts
}
if atts.frame.origin.x - 1 <= self.sectionInset.left {
return atts
}
let ipPv = IndexPath(item:indexPath.row-1, section:indexPath.section)
let fPv = self.layoutAttributesForItem(at:ipPv)!.frame
let rightPv = fPv.origin.x + fPv.size.width + self.minimumInteritemSpacing
atts = atts.copy() as! UICollectionViewLayoutAttributes
atts.frame.origin.x = rightPv
return atts
}
}
答案 1 :(得分:1)
所以我遇到了同样的问题,我开始探索苹果的 this 项目,我认为这是一个错误,在 viewWillAppear 中滚动到集合视图中的第一项解决了这个问题。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if collectionView.numberOfItems(inSection: 0) > 0 {
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: false)
}
}