I'm trying to change the height of a UILabel
depending on how much text is in the label.
I can calculate the size required for the label but when I try to set the UILabel
frame it just doesn't change.
Below is my code.
Even if I replace size.height in the last line to something like 500 the size of the UILabel
frame doesn't change
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"GameItemCell";
GameItemCell *cell = (GameItemCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"GameItemCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
GameItem* item = [_hunt.gameItems objectAtIndex: indexPath.row];
cell.itemHeaderLabel.text = [NSString stringWithFormat:@"#%d - (%d pts)", indexPath.row+1, item.itemPoints];
UILabel* textLabel = cell.itemTextLabel;
textLabel.text = item.itemText;
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGRect frame = cell.itemTextLabel.frame;
CGSize textSize = { frame.size.width, 20000.0f };
CGSize sizeOneLine = [@"one line" sizeWithFont:cell.itemTextLabel.font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGSize cellTextSize = [item.itemText sizeWithFont:cell.itemTextLabel.font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGSize sizeOneLineSpacing = CGSizeMake(sizeOneLine.width, sizeOneLine.height + 3);
NSInteger lines = cellTextSize.height / sizeOneLine.height;
CGSize size = CGSizeMake(frame.size.width, lines * sizeOneLineSpacing.height);
textLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, size.width, size.height);
return cell;
}
You must set the frame of your label in GameItemCell inside -(void)layoutSubviews
Instead of doing all that hard work, try it like:
textLabel.numberOfLines = 0;
textLabel.text = textString;
[textLabel sizeToFit];
remember sizeToFit
respect your labels default width, so set width according to your requirement. And then Height will be managed by the sizeToFit
method.
In the end you will need to put something like these two methods in your UITableViewCell subclass:
// call this method on your cell, during cellForRowAtIndexPath
// provide your resizing info (frame, height, whatever)
- (void) updateLabelFrame:(CGRect)newLabelFrame {
self.resizedLabelFrame = newLabelFrame;
[self setNeedsLayout];
}
// the actual resize happens here when UIKit gets around to it
- (void) layoutSubviews {
[super layoutSubviews];
self.myLabel.frame = self.resizedLabelFrame;
}
You have missed numberOfLines
property to set.
Add :
textLabel.numberOfLines = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With