嘗試通過子類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
}
}
使用它,我知道這是一個很瑣碎的問題,但我不敢問吧。您是否正確地將您的自定義類分配給了collectionView的佈局? – Adeel
感謝您詢問:-)如果您有時間,請查看此Playground:https://github.com/JCzz/CollectionView總的來說,我只是試圖在屏幕中心縮放視圖。 –
@ ChrisG.I'm有同樣的問題。一切似乎很好,除了「LayoutAttributesForItem」根本不會觸發。我不知道爲什麼。 – jnel899