Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply different contentInset only for contents cells but not for a header in UICollectionView

I use insetForSectionAtIndex method to set contentInset for a section in my collection view and I don't want to apply that inset to a header of the section. I need the header width to be as wide as the screen.

ConentInset

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    if section == 1 {
        return UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
    }

    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

Header

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: opsMainDescriptionSegmentedControlCellId, forIndexPath: indexPath) as! MyHeader

    return header
}
like image 548
Bigair Avatar asked Jul 20 '16 07:07

Bigair


2 Answers

I just had to do this exact same thing in one of my project.

The solution I applied:

In Storyboard, my collection view takes up the full screen with Auto-Layout constraints.

In viewDidLoad:

collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

I set the collectionView delegate to self and also conform to the

UICollectionViewDelegateFlowLayout protocol.

You then have access to the method you've used where I return another UIEdgeInsets

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets(top: 15, left: 20, bottom: 15, right: 20)

    }

and it worked for me.

See how it looked in the end.

enter image description here

Hope this will be able to help others.

like image 183
Edouard Barbier Avatar answered Sep 27 '22 17:09

Edouard Barbier


You cannot do this. UICollectionViews headers need to be as wide as the UICollectionView itself. If you want the header to be shorter (width) than the UICollectionView - my suggestion is to use a separate UIView inside the header and set the header to clear. That way it will appear that its shorter than the width of the UICollectionView.

like image 41
Robert J. Clegg Avatar answered Sep 27 '22 16:09

Robert J. Clegg