ichanduu ichanduu - 3 months ago 16
Swift Question

UIcollectionView Spacing

I have 10 cells out of which the width of the 6th cell has to be different from others.I tried to change it in the flow delegate method. but something is going wrong with the spacing from 7th to 10th cell.

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

let widthOfCollectionView = collectionView.bounds.width - 40;

// For collectionView use "item" instead of "row"
if indexPath.item == 6{
return CGSizeMake(widthOfCollectionView,100)
}else{
return CGSizeMake(widthOfCollectionView/3, 100)
}
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {

return 10;
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10;
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{

return UIEdgeInsetsMake(5, 5, 5, 5);
}


enter image description here

Answer

For the width of small items you should return (collectionView.bounds.width - 30)/3, 5 for left inset, 5 for right inset and 2*10 for spacing = 30.
For the width of large item you should return collectionView.bounds.width - 10, 5 for left and 5 for right inset = 10.

You can replace this

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

    let widthOfCollectionView  = collectionView.bounds.width - 40;
    if indexPath.item == 6{
        return CGSizeMake(widthOfCollectionView,100)
    }else{
        return CGSizeMake(widthOfCollectionView/3, 100)
    }
}

With

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

    let smallItemWidth = floor((collectionView.bounds.width - 30)/3 * 1000) / 1000
    let largeItemWidth = collectionView.bounds.width - 10

    if indexPath.item == 6{
        return CGSizeMake(largeItemWidth, 100)
    }else{
        return CGSizeMake(smallItemWidth, 100)
    }
}

*Use floor() to round down large decimals

Comments