4

I have a UITableView and a Cell which I design with Interface Builder. I have two labels there. The problem is, that one of the labels is text which can be 500 words or 10 words.

So I need a dynamic cell height. How can I handle this, because otherwise I have empty space or the cell height is not enough.

Perhaps someone has an idea how to do this?

Best Regards.

Tim
  • 13,228
  • 36
  • 108
  • 159

2 Answers2

5

To know the size of your text, you can use this method:

- (CGFloat)measureTextHeight:(NSString*)text fontName:(NSString*)fontName fontSize:(CGFloat)fontSize constrainedToSize:(CGSize)constrainedToSize {
CGSize mTempSize = [text sizeWithFont:[UIFont fontWithName:fontName size:fontSize] constrainedToSize:constrainedToSize lineBreakMode:UILineBreakModeWordWrap];
return mTempSize.height; }

Then you can set your size cell with:

-(CGFloat)tableView:(UITableVIew*)tableView heightForRowAtIndexPath(NSIndexPath *)indexPath;
Ludovic Landry
  • 11,606
  • 10
  • 48
  • 80
  • Hm, isn't it possible to read all values from the UILabel field? because if I change a size, I havealso to change it here, and what is the `constrainedToSize`? – Tim Feb 01 '11 at 16:56
  • constrainedToSize is the width of your screen (or your UILabel if it does not fit the screen width). – Ludovic Landry Feb 01 '11 at 17:06
  • 1
    Ah, okay, it seems to work, but where and how can I resize the UILabel? – Tim Feb 01 '11 at 17:14
  • You just need to change your UILabel frame. With something like this : label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, constrainedToSize.width, [self measureTextHeight:label.text fontName:fontName fontSize:fontSize constrainedToSize:constrainedToSize]); – Ludovic Landry Feb 01 '11 at 17:20
2
-(CGFloat)tableView:(UITableVIew*) tableView heightForRowAtIndexPath(NSIndexPath *) indexPath
{
   //here u can check the row number and ur labels and return ur custom height.
}
James Kuang
  • 10,710
  • 4
  • 28
  • 38
Ratinho
  • 298
  • 1
  • 6
  • Yes, that's clear, but how can I check these heights of the labels? Because I define it in the IB with i.e. 40px, this is then a fix size. So if I ask for the Label height, I will get always 40px. – Tim Feb 01 '11 at 16:47
  • good question...i have no any nice ideas...only ugly one that u can count the chars and guess based on ur font what will be its height:S – Ratinho Feb 01 '11 at 16:55