Search code examples
iosobjective-cuicollectionviewwidthcgsize

Adjust cell width based on text - UICollectionView - iOS


I have an iOS app with a UICollectionView which presents cells horizontally. In each of the cells, I have added one simple label (for now). These labels are showing names, sometimes the names are short and thats fine... but.... sometimes the names are long and are thus cut off because they cannot fit properly within the width of the collection view cell.

Is there a way to adjust the width of the cell/label dynamically so that the name text will be shown properly?

I was experimenting using this method:

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(106.f, 60.f);
}

But I have two main problems with the above method:

  1. How do I access the cell label from this method? (So that I can get its height).
  2. How do I actually figure out what the width of the cell/label needs to be?

Thanks for your time,

Dan


Solution

  • Thanks to everyone for posting, in the end the solution that worked for me was a mix of all your solutions and a bit of extra "tinkering":

    -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        // Get the user name and profile name strings.
        NSString *user_label = [NSString stringWithFormat:@"%@", [user_data[indexPath.row] objectAtIndex:0]];
        NSString *name_label = [NSString stringWithFormat:@"%@", [user_data[indexPath.row] objectAtIndex:1]];
    
        // Calculate the contact text widths.
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"SFUIDisplay-Thin" size:20.0f]};
        CGRect rect = [user_label boundingRectWithSize:CGSizeMake(MAXFLOAT, 60) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        CGRect rect_two = [name_label boundingRectWithSize:CGSizeMake(MAXFLOAT, 60) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    
        // Add the other cell objects width to
        // the biggest calculated text width.
        CGFloat row_width = 0;
    
        if (rect.size.width > rect_two.size.width) {
            row_width = (rect.size.width + 55);
        }
    
        else {
            row_width = (rect_two.size.width + 55);
        }
    
        // Only return the generated width if
        // it is bigger than the original width.
    
        if (row_width > 106) {
            return CGSizeMake(row_width, 60.f);
        }
    
        else {
            return CGSizeMake(106, 60.f);
        }
    }