Xingxing Xingxing - 6 months ago 28
Objective-C Question

UICollectionView add gap between cells

I'm using

ALAssetsLibrary
to access system photo library to preview and multiple select photos,which is like the origin system photo library and I can scroll to preview photos.I implement it by
UICollectionView
and
UICollectionViewFlowLayout
.Everything goes well except a little issue.

When I use iOS system photo library and scroll to preview photos,there is a Gap between two photos like below.
enter image description here

While in my app,there is is no Gap between the two photos when scrolling.I set
UICollectionView
paged and
UICollectionViewFlowLayout
cell space(
minimumLineSpacing
and
minimumInteritemSpacing
) to zero both.
enter image description here

How can I make my photo preview like system photo library with a Gap between two scrolling photos?I am new to
UICollectionView
,and I am not sure if the Gap is implemented by
SupplementaryView
or anything else.

Answer

This can be done in

  1. Set the UICollectionView frame width larger than screen width.

    layout = [[UICollectionViewFlowLayout alloc]init];
    CGRect cSize = self.view.bounds;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    // 1. UICollectionView frame width lager than screen with => Screen width + 2*(required Space)
    cSize.size.width += 20; 
    self.collectionGallery = [[UICollectionView alloc]initWithFrame:cSize collectionViewLayout:layout];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
  2. Set UIImageView frame width equal to screen width.

    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GalleryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    
    cell.imageGallery.contentMode = UIViewContentModeScaleAspectFit;
    // 2
    cell.imageGallery.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    return cell;
    }
    
  3. Cell width should be larger than screen width, same as in step 1.

    -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeMake(self.view.frame.size.width + 20, self.view.frame.size.height); // cell size should be same as collectionview width
    return size;
    }
    

Hope this will help you. Please do comment and vote up if this solves your problem

Comments