Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView insetForSectionAtIndex not being called

I have a class with the following declaration and constructor:

class GameView: UIView, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
    var collectionView: UICollectionView?
    var flowLayout =  UICollectionViewFlowLayout()

    init (frame : CGRect, navigationController:UINavigationController, parentViewController: ScrambleViewController)
{
    super.init(frame : frame)
    cvFrame = CGRect(x: cvLeftBorder, y: cvY, width: Int(UIScreen.main.bounds.width) -  (2 * cvLeftBorder), height: cvHeight)
    collectionView = UICollectionView(frame: cvFrame!, collectionViewLayout: flowLayout);
    collectionView!.dataSource = self
    collectionView!.delegate = self;
    .....
}

This is a game where there is a different number of cells each round. I want to center the cells, so I inserted:

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

 // calculate the insets and return a UIEdgeInsets
}

For some reason, the function is never called. Otherwise, the program is working fine. Or is there a better way to center the cells in each round?

Thanks in advance.

like image 768
Jonathan Rachlin Avatar asked Dec 08 '16 06:12

Jonathan Rachlin


2 Answers

This will work:

@objc(collectionView:layout:insetForSectionAtIndex:)  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
    return UIEdgeInsetsMake(5, 5, 5, 5)
}
like image 184
Eyzuky Avatar answered Sep 29 '22 10:09

Eyzuky


Don't forget to add UICollectionViewDelegateFlowLayout

like image 39
Can Aksoy Avatar answered Sep 29 '22 11:09

Can Aksoy