Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView: add spacing between header and items

Tags:

I want to add some spacing between my header and the actual items, which currently look like this:

screenshot1

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {     // Create header     switch kind{         case UICollectionElementKindSectionHeader:             let headerView = iconCollectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "customIconHeaderView", forIndexPath: indexPath) as! CustonIconHeaderView             headerView.setUp() //add whatever into the view             return headerView         default:             assert(false, "Unexpected element kind")     }  } 
like image 343
Liumx31 Avatar asked Jan 27 '16 17:01

Liumx31


1 Answers

You are basically talking about adding a top margin to the collection view section, for that you would set top inset for the section. To do it in code, implement insetForSectionAtIndex:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {     return UIEdgeInsets(top: 10.0, left: 1.0, bottom: 1.0, right: 1.0) } 

If you don't want to implement the insetForSectionAtIndex, you could also do something like this in an appropriate method e.g. viewDidLoad:

let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsets(top: 10.0, left: 1.0, bottom: 1.0, right: 1.0) 

In Interface Builder, Select collection view and change the value for Section Insets -> Top as shown in the image below:

enter image description here

NOTE: This only works if you are using Flow Layout.

like image 187
ishaq Avatar answered Oct 08 '22 06:10

ishaq