2

I have a custom UITableViewCell with a UILabel inside on the Storyboard. I set the text of this UILabel dynamically and I need to resize the width of the UILabel accordingly because after it I have another UILabel that must stay side to side.

I am trying with

> MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
> author = @"Some dynamic text";
> cell.authorLabel.text = author;
> [cell.authorLabel sizeToFit];

What happens: at the first render the UILabel just keeps the width that is set on the storyboard, thus either the text is cropped or there is too much space after it.

After scrolling, the cells are dequeued and the sizeToFit method is applied properly, but is too late because the second UILabel is already positioned on the wrong place. (cannot post picture due to low reputation restriction)

Any idea?

stilllife
  • 1,776
  • 1
  • 18
  • 38
  • see [this question](http://stackoverflow.com/questions/1947970/dynamic-calculation-of-uilabel-width-in-uitableviewcell?rq=1) – Lithu T.V Jul 22 '13 at 12:25

2 Answers2

2

maybe you mean something like that:

MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
author = @"Some dynamic text";
cell.authorLabel.text = author; <-- excluded in your code
[cell.authorLabel sizeToFit];

If this doesn't work, try to use some like this:

subclass UITableViewCell and rewrite the method below:

- (void)setSelected:(BOOL) selected
{ 
    [super setSelected:selected];
    [self.authorLabel sizeToFit];
}
user2595925
  • 108
  • 5
1

use this one for getting dynamic height and width,

CGSize sizeDynamic  = [str sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:14] constrainedToSize:CGSizeMake(CGFLOAT_MAX,CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

you can get,

sizeDynamic.height and sizeDynamic.width values
Balu
  • 8,470
  • 2
  • 24
  • 41
  • This works to properly resize the `UILabel` based on the content, but I still have the problem that in this way the side-by-side label is not moved so it doesn't respect the horizontal spacing constraint and the final result is two text overlapping. Should I calculate the new position of the second label based on the new width of the first label? N.B. If this `sizeWithFont` works and `sizeToFit` on the same point doesn't work, what am I missing about `sizeToFit` method? – stilllife Jul 23 '13 at 08:56