jeudi 23 juin 2016

Subclassing UICollectionViewFlowLayout for static cells

there is some small customization I want to add to UICollectionViewFlowLayout, nothing major that requires a completely new layout, but enough to get the logic outside the collectionView delegate methods.

Essentially, I have a few different button layouts that look like this.

--------       
-Button-       -Button-Button-
-Button-       -Button-Button-
-Button-       -Button-Button-
--------       

So I need the cell's size to be dynamic to how many cells there are. If there are more than 4 cells I want them to appear two per row. I currently have this working with the delegate method like so.

func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                           sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let carouselIndex = collectionView.tag
    let responses = questions[carouselIndex]

    let height = collectionView.frame.size.height/4 - 5
    var width: CGFloat
    if (responses.count > 4) {
        width = collectionView.frame.size.width/2 - 3
    }
    else {
        width = collectionView.frame.size.width
    }
    return CGSizeMake(width, height)
} 

However, I am going to be needing to add more custom sizes and functionality in the future and thought it might be best to create a custom Layout.

I really want to keep all the same functionality as Flow Layout, and just override the cell sizes. Here is my poor attempt at doing so.

class SurveyFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let superAttributes = super.layoutAttributesForElementsInRect(rect)

        for attributes in superAttributes! {
            let itemCount = collectionView?.numberOfItemsInSection(0)
            let cellHeight = collectionView!.frame.size.height/4 - 5
            let cellWidth: CGFloat
            if (itemCount > 4) {
                cellWidth = collectionView!.frame.size.width/2 - 3
            }
            else {
                cellWidth = collectionView!.frame.size.width
            }
            attributes.frame = CGRectMake(attributes.frame.origin.x, attributes.frame.origin.y, cellWidth, cellHeight)
        }
        return superAttributes
    }

    override func prepareLayout() {
        super.prepareLayout()
    }  
}

What needs to be done to only customize cell sizes programmatically?

Aucun commentaire:

Enregistrer un commentaire