Chris G.
Chris G.

Reputation: 25964

UICollectionViewLayout and method layoutAttributesForItem is never called

I am trying to implement a UICollectionViewFlowLayout or UICollectionViewLayout - any ways the layoutAttributesForItem is never called.

I can see from others that they call layoutAttributesForItem from self.layoutAttributesForItem.

Like this flowout example:

I have created a Playground project you can look at. Overall I am just trying to scale up the center view.

Upvotes: 14

Views: 7555

Answers (1)

kalpesh jetani
kalpesh jetani

Reputation: 1803

Try to use it by 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
    }

}

Upvotes: 7

Related Questions