Search code examples
iosuicollectionviewcell

UICollectionView - Where to design each cell. Frames given doesnt work properly


I want to create 3 cells in each row, with width & height 104.0f each. But I am getting the output as shown in the screenshot.

The code used is given below. Since I am new to UICollectionView, I have no idea how to implement this. Where do I design the cells incase if frames are different for all?

Screenshot

- (void)viewDidLoad
{
    ....
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    dealListCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(1.0f, 1.0f, 320.0f, 525.0f) collectionViewLayout:layout];
    [dealListCollectionView setDataSource:self];
    [dealListCollectionView setDelegate:self];

    [dealListCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [dealListCollectionView setBackgroundColor:[UIColor lightGrayColor]];

    [self.view addSubview:dealListCollectionView];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

return 10;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    return CGSizeMake(104, 104);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

    return UIEdgeInsetsMake(0, 0, 0, 0);
}


- (UIEdgeInsets)insetsForItemAtIndexPath:(NSIndexPath *)indexPath {

    return UIEdgeInsetsMake(2, 2, 2, 2);
}

Solution

  • The below code solved my problem :

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