I am working with a UICollectionView
using UICollectionViewFlowLayout
and have some difficulties to understand item sizing an spacing. I know that there several methods to adapt sizing and spacing (using the delegate methods, overriding FlowLayout, etc.). However without understanding the logic behind these values in the first place, it is quite hard to adapt them properly.
The following results have been created a default UICollectionViewController
with a default UICollectionViewCell
without any subclasses. Only the following settings haven been made:
- Specified the cell size to be 200 x 200 in IB
- Placed a Label inside the cell and centered in vertically and horizontal
Code:
private let reuseIdentifier = "Cell"
class MyViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
var layout: UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 5
layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)
layout.sectionInsetReference = .fromContentInset
return layout
}
collectionView.collectionViewLayout = layout
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
return cell
}
/*func collectionView(_ collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:IndexPath) -> CGSize {
var width = view.frame.width
return CGSize(width: collectionVw.frame.size.height, height: collectionVw.frame.size.height)
}*/
}
Using different values for layout.minimumInteritemSpacing = 5
creates results I do not understand:
Why are the items 50 x 50px in size? I know that one can useSolved in the answer by @Larme...sizeForItemAt
to specify explicit dimensions. However, setting the size in IB should also work, shouldn't it? Why is the IB size of 200 x 200px ignored? Why 50x50, is this the default size or where is this specified?- I know that
minimumInteritemSpacing
does not set the explicit spacing but only a minimum. However, how is the value computed? - Why is the a spacing of
7.5px
for a value of 5? Why result values 10-25 result all in the same a spacing of26.5px
?
So: How exactly are sizes and spacing computed here?