I would like to be notified when my custom UICollectionView gets its size. It is created from xib. I've added the following function:
override func layoutSubviews() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: segmentWidth(), height: segmentHeight())
self.setCollectionViewLayout(layout, animated: false)
}
This function is called endlessly. What am I doing wrong?
You shouldn't need to update the layout like this when the collection view changes.
In fact, because you're using a Flow Layout there should be a much easier way of getting it to do what you want.
I presume that segmentHeight
and segmentWidth
are functions that depend on the size of the collection view which is why you need to recalculate them?
If so then you should be able to use the delegate
functions of the UICollectionViewFlowLayout
.
First update your view controller with a new protocol...
class MyViewController: UICollectionViewDelegateFlowLayout
This will then let your view controller act as a delegate for the flow layout.
And use the method...
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
return CGSize(width: segmentWidth(), height: segmentHeight())
}
That should be it.
If I've missed anything out let me know but you should get everything you want from that.
After that just delete the layoutSubviews
method and it should be performing as you want.