I've got a UICollectionView
that will have cells with labels of varying sizes. I'm trying to size the cell based on the size of the label. However sizeForItemAtIndexPath
where I create the cell seems to be called before cellForItemAtIndexPath
where I set the label.. Any ideas what I can do here?
- (void)getLabelSize:(UILabel *)label {
float widthIs = [label.text boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:label.font } context:nil].size.width;
width = widthIs;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
UILabel *label = (UILabel *)[cell viewWithTag:1000];
label.text = @"This is pretty long";
[label sizeToFit];
[self getLabelSize:label];
NSLog([NSString stringWithFormat:@"%f", width]);
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(width, 50);
}
You need to store text for labels somewhere, in array for example, and separately define font for labels and define maxWidth, something like:
Then modify method getLabelSize, with string as an argument:
Then you can get the size from both methods cellForItemAtIndexPath and sizeForItemAtIndexPath:
Its solution for Swift 4.2 updated answer is to handle height and width of uicollectionview Cell on the basis of uilabel text
In swift i have calculated the text size of label and updated the cell size according to it:
as i have an extra button and padding i calculated that extra value which is 45.0
First you have to store your message in a temp label (make sure it is hidden or not visible). Then get that label width and height as below: