Martin Koles
Martin Koles

Reputation: 5247

UICollectionViewCell with flexible width

I have a basic collection view with vertical scrolling, sections and variable amount of cells in each section. I need to adjust the width of each cell to fill available width of the view up to 4 cells, when I need to start next row of cells.

If a section has 1, 2, 3 or 4 cells, their width should be 1/1, 1/2, 1/3 or 1/4 of the view's width respectively. Sections with more then 4 cells should stretch 4 cells in one row and continue on the other row.

Do I need to subclass UICollectionViewFlowLayout for this or can I handle it in UICollectionViewController class and how?

enter image description here

Upvotes: 2

Views: 877

Answers (2)

Sunny Shah
Sunny Shah

Reputation: 13020

You should work with below two methods to change the column in one row

 - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5,5,0,5);
}

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

    return CGSizeMake(75, 75);
}

Upvotes: 3

Yohan
Yohan

Reputation: 1108

You have to play with UICollection view Delegate methods to give a custom design for CollectionCell

- (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;
}


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

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

and size you can set in Frame File inspector enter image description here

Upvotes: 0

Related Questions