Reputation: 1074
Im trying to get my collectionView cells to look like the picture bellow but have not been able to do it. I tried using collectionViewLayout but was not able to get the sizing right along with the proper padding. How would I be able to do this?
Here is my code
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameSize = collectionView.frame.size
return CGSize(width: frameSize.width, height: frameSize.height / 2)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 27, bottom: 0, right: 27)
}
}
Here is a picture of what I'm trying to achieve. Thanks
Upvotes: 4
Views: 4728
Reputation: 8011
Implement the UICollectionViewFlowLayout
's following methods
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
and for the 27px inset use
yourcollectionView.sectionInset = UIEdgeInsets(top: 10, left: 27, bottom: 10, right: 27)
To use you class which implements this protocol, you have to set the collection view's delegate property.
yourcollectionView.delegate = /* object which implement flow layout delegate */
UICollctionViewDelegate
automatically conform to UICollectionViewFlowLayoutDelegate
, setting the delegate is enough.
You are missing another thing while calculating the cell size. Your cell size calculation is wrong. Implement it as follows
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameSize = collectionView.frame.size
let size = (frameSize.width - 64.0) / 2.0 // 27 px on both side, and within, there is 10 px gap.
return CGSize(width: size, height: size)
}
If you are using the storyboard to set layout your UI Widget, you can set them in storyboard too.
Upvotes: 6