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
}
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.
Hope this will be able to help others.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With