sanjana Mishra sanjana Mishra - 3 months ago 18
iOS Question

how to make dynamic width of the UICollectionViewCell

I am new to ios and want to set dynamic width of uicollectionview cell.
I have found some code in swift and i want the code in objective C.

let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
if indexPath.item % 3 == 0 {
let cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right))
return CGSize(width: cellWidth, height: cellWidth / 2)
} else {
let cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) - flowLayout.minimumInteritemSpacing) / 2
return CGSize(width: cellWidth, height: cellWidth)
}


Thanks.

Answer

You can try this...

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

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
if (indexPath.item % 3 == 0) {
    float cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right));
    return CGSizeMake(cellWidth, cellWidth / 2);
} else {
    float cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) - flowLayout.minimumInteritemSpacing) / 2;
    return CGSizeMake(cellWidth, cellWidth);
}
}