Jason John
Jason John

Reputation: 936

UICollectionView Wrap Cell around Label

I need to be able to wrap a UICollectionViewCell around a Label (with some padding). Basically, I'm looking for something like this (this is done on Android, without much hassle): enter image description here

This is what I have so far in my UICollectionView. Each cell is a set width (screen width / 3) but in the end I want each cell to be the width of the label (+ some extra padding):

enter image description here

I tried override sizeForItemAtIndexPath

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) //returns nil
    var width = cell?.bounds.width
    return CGSizeMake(width!, 50)

}

Any tips? Thank you!

Upvotes: 3

Views: 579

Answers (1)

Mandal Tsaschikher
Mandal Tsaschikher

Reputation: 11

In sizeForItemAtIndexPath return the size of the text

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

    return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];
}

Upvotes: 1

Related Questions