Andrei Stanca
Andrei Stanca

Reputation: 908

How to make UICollectionViewFlowLayout stay inside a UICollectionView

I have built a custom calendar using collection view. My problem is that when I add UICollectionViewFlowLayout it covers the whole screen and doesn't stay inside UICollectionView. How do I make the UICollectionViewFlowLayout stay inside UICollectionView? Here is my code:

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 100, left: 10, bottom: 1, right: 10)
    let width = UIScreen.mainScreen().bounds.width
    layout.itemSize = CGSize(width: width/10, height: 35)

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
    collectionView!.backgroundColor = UIColor.whiteColor()

    self.view.addSubview(collectionView!)

Where I want the calendar to be:

Where I want the calendar to be

This is how it covers the whole screen:

enter image description here

Upvotes: 1

Views: 452

Answers (1)

pbasdf
pbasdf

Reputation: 21536

This line:

collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

is creating a new instance of UICollectionView, and setting its frame to be the same as self.view (hence it covers the full screen). I suspect you actually want to use an existing instance of collection view which is established in a storyboard (and is probably being presented - but behind the new one!). Check in your storyboard to see whether the CollectionView is hooked up to the collectionView property of your view controller:

Screenshot

If so, you can just comment out the above line (and possibly the next two lines as well), since the links will be established when your view controller is instantiated.

If you do not have a storyboard instance, then just amend the frame to suit the position and size that you want, rather than using self.view.frame.

Upvotes: 2

Related Questions