I've been searching on google & stackoverflow for a while trying to accomplish a fairly simple action on my UICollectionViewCells
but until now I've not been able to do it.
What I want to have is a CollectionViewController
with two cells for each row. Each cell must have the same margin on top, left, bottom and right sides.
Until now what I have is:
The thing is that I want to have the same amount of margin in each side of the cell. That means that the EdgeInsets
left and right both have to be 14 not 7..
I am not able to accomplish this.. I know that I'm missing something but I can't figure out what is.
I am using a FlowLayout
, this is the code of the UICollectionViewDelegateFlowLayout
fileprivate let phoneSectionInsets = UIEdgeInsets(top: 14.0, left: 7.0, bottom: 20.0, right: 7.0)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let phoneHeight = 250
let fixedWidth = 220
return CGSize(width: (collectionView.bounds.size.width / 2 - (phoneSectionInsets.left + phoneSectionInsets.right)), height: CGFloat(phoneHeight))
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return phoneSectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 14.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 14.0
}
If I set the edge insets from left and right to 14 then I have 14 margin on the right and left sides but in between cell I have 28..
Thank you so much for the help.
You need to cross check your code in sizeforitem
fileprivate let phoneSectionInsets = UIEdgeInsets(top: 14.0, left: 14.0, bottom: 20.0, right: 14.0)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let phoneHeight = 250
let fixedWidth = 220
return CGSize(width: (collectionView.bounds.size.width - (phoneSectionInsets.left + phoneSectionInsets.right + 14/*item spacing */))/2.0, height: CGFloat(phoneHeight))
}
while calculating item width you need to consider left and right margin along with item in between spacing.