UICollectionView 3 column grid, 1px space?? (image included)

放肆的年华 提交于 2019-11-30 11:19:56

Better avoid number's double type in similar situations. Use:

return CGSizeMake(ceil(totalWidth), ceil(totalHeight))

I was having the same problem, I fixed it with the code below:

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let paddingSpace = sectionInsets.left * 4
    let availableWidth = view.frame.width - paddingspace
    let widthPerItem  = availableWidth/3

    return CGSizeMake(width: widthPerItem, height: widthPerItem)
}

and define the variable below in the begin of your class:

fileprivate let sectionInsets = UIEdgeInsets(top: 0.0, left: 0.5, bottom: 0.0, right: 0.0)

For example you have screen width = 320, when you divide it by 3 you have 106.6666. If consider it as Int, we have: 106 * 3 = 318. We need 2 pixel to be added by 1 px to first two cells because 320 - 318 = 2. Try this solution below.

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let columns = 3 
    let width = Int(UIScreen.main.bounds.width)
    let side = width / columns
    let rem = width % columns
    let addOne = indexPath.row % columns < rem
    let ceilWidth = addOne ? side + 1 : side
    return CGSize(width: ceilWidth, height: side)
}
Zara Mehboob Ali

Here is my solution to issue just make middle cell of width 106 and other two with width 107 in method collectionView layout

NSInteger numColumns = 3;
CGSize deviceSize;
CGFloat width = self.view.frame.size.width / numColumns;
CGFloat height = width ;
NSInteger rem = (int)self.view.frame.size.width%numColumns; 
if(indexPath.row == (1 + numColumns*counter) && rem != 0) {  

    deviceSize = CGSizeMake(floor (width), ceil(height));
    counter++;
}
else {

    deviceSize = CGSizeMake(ceil (width), ceil(height));
}
deviceSize = CGSizeMake(deviceSize.width, deviceSize.height);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!