Dynamic width of UIcollectionviewCell in iOS?

177 Views Asked by At

I had an application in which I am taking the width of the collection view cell as:

- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(20, 20,20,20);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect screenRect = collection.frame;
    CGFloat screenWidth = screenRect.size.width;
    float cellWidth = screenWidth / count;
}

But now I want on that count the width of the cell needs to be dependent on one parameter, like:

NSDictionary *dict=[arr objectAtIndex:indexPath.item];
    float duration=([[dict valueForKey:@"duration"]floatValue]);

If duration is 45 then it needs to take 45% of the screen width and like that. Can anybody help me on This when i am trying screenWidth * (duration/100.0) it is looking like this

enter image description here

2

There are 2 best solutions below

6
On

If You collectionview just consist of this cells, then i would recommend you to go with section approach. multiple section for each item , and each section has only one row . By this approach there will be only one row in section and as you wanted even if row size is 10% or less.

keep size approach like below.

NSDictionary *dict=[arr objectAtIndex:indexPath.item];
float duration=([[dict valueForKey:@"duration"]floatValue]);
float cellWidth = screenWidth * (duration/100.0);
0
On
    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CGRect screenRect = collection.frame;
        CGFloat screenWidth = screenRect.size.width;
        NSDictionary *dict=[arr objectAtIndex:indexPath.item];
        float duration=([[dict valueForKey:@"duration"]floatValue]);
        float cellWidth = duration / 100;

return CGSize(cellWidth, 60);
    }

It helps you.