Jiang Xiang
Jiang Xiang

Reputation: 3256

UICollectionViewDelegateFlowLayout insets does not work

I have implemented UICollectionViewDelegateFlowLayout in my ViewController, and specify insets using the following code:

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

But this function is never executed when I use breakpoints to debug. As I have already specified the delegate of the UICollectionView to the ViewController, I do not know what is going wrong.

Upvotes: 2

Views: 2213

Answers (1)

torinpitchers
torinpitchers

Reputation: 1292

To set layouts for a collection view, do the following inside the collectionViewClass:

1. implement the method getLayout:

func getLayout() -> UICollectionViewLayout
    {
        let layout:UICollectionViewFlowLayout =  UICollectionViewFlowLayout()

        layout.itemSize = CGSize(width: 150, height: 150)
        layout.sectionInset = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)

        return layout as UICollectionViewLayout

    }

2. set property from method in ViewDidLoad:

self.collectionView!.collectionViewLayout = self.getLayout()

Upvotes: 6

Related Questions