2016-10-19 56 views
7

我試圖實現一個UICollectionViewFlowLayoutUICollectionViewLayout-任何方式都不會調用layoutAttributesForItemUICollectionViewLayout和方法layoutAttributesForItem永遠不會被調用

我可以從別人那裏看到他們從self.layoutAttributesForItem打電話給layoutAttributesForItem

this flowout例如:

我創建了一個Playground項目,你可以看看。總的來說,我只是想擴大中心觀點。

+0

使用它,我知道這是一個很瑣碎的問題,但我不敢問吧。您是否正確地將您的自定義類分配給了collectionView的佈局? – Adeel

+0

感謝您詢問:-)如果您有時間,請查看此Playground:https://github.com/JCzz/CollectionView總的來說,我只是試圖在屏幕中心縮放視圖。 –

+0

@ ChrisG.I'm有同樣的問題。一切似乎很好,除了「LayoutAttributesForItem」根本不會觸發。我不知道爲什麼。 – jnel899

回答

1

嘗試通過子類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 
    } 

} 
+0

那麼你真正在這裏提出的是我們自己調用'layoutAttributesForItem(at:)'而不是依賴'UICollectionViewFlowLayout'並期待它回調? :/ –

+0

@MohammadAbdurraafay是的,如果我們正在使用自定義流程佈局,那麼它會調用這個重寫功能。 –

+0

這是在Internet上的最好的例子(我可以找到)layoutAttributesForItem在swift中。 –

相關問題