Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal spacing for collectionview items in ios

I using collection view controller to display images like in gallery. Now I struck with spacing. I cant set equal spacing in collection view..

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(106.0f, 106.0f);
}

This is my code.. cell width 106 but the imageview width is 104.0f I gave 2 points spacing left side of the image view now I got solution as below image. enter image description here

Pls help me to fix this problem...

like image 540
Seeker Avatar asked Jun 21 '14 04:06

Seeker


1 Answers

Swift 5

Set up some section insets (How far your cells will be from the frame of the CollectionView), number of cells you want in a row, and the spacing you want between your cells

let sectionInsets = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0)
let numberOfItemsPerRow: CGFloat = 4
let spacingBetweenCells: CGFloat = 10

Use all the values above in the UICollectionViewDelegateFlowLayout:

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let totalSpacing = (2 * sectionInsets.left) + ((numberOfItemsPerRow - 1) * spacingBetweenCells) //Amount of total spacing in a row

        if let collection = self.collectionView{
            let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
            return CGSize(width: width, height: width)
        } else {
            return CGSize(width: 0, height: 0)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return spacingBetweenCells
    }
like image 148
Danil Kurilo Avatar answered Oct 13 '22 01:10

Danil Kurilo