iOS - UICollectionView spacing still there when set to 0 - How to set with no spacing between cells
Simple solution for your Query. Add this in your viewController's .m file:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ ProductDetailViewController *HomeVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductDetailView"]; HomeVC.title = @"DemoProject"; [self.navigationController pushViewController:HomeVC animated:YES];}- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right}- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 0.0;}- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 0.0;}
Swift 3 version of @MihirOza 's solution
Worked for both Horizontal and Vertical collection views
Code
// removing spacingfunc collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.0}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.0}
You have to create custom UICollectionViewLayout
.
Space between the cells will be equal to cellSpacing
.
final class CustomFlowLayout: UICollectionViewFlowLayout { let cellSpacing: CGFloat = 0 override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let attributes = super.layoutAttributesForElements(in: rect) { for (index, attribute) in attributes.enumerated() { if index == 0 { continue } let prevLayoutAttributes = attributes[index - 1] let origin = prevLayoutAttributes.frame.maxX if (origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) { attribute.frame.origin.x = origin + cellSpacing } } return attributes } return nil }}