Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

heightForRowAtIndexPath for longer NSStrings

I have a UITableView (Grouped!) and need to calculate the height of two styles of cells: UITableViewCellStyleDefault and UITableViewCellStyleValue2.

This is how I do it for UITableViewCellStyleDefault:

CGSize  textSize = {300.f, 200000.0f};
CGSize  size = [myTextString1 sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
size.height += 30.0f;
result = MAX(size.height, 44.0f);

And for UITableViewCellStyleValue2:

CGSize  textSize = {207.f, 200000.0f};
CGSize  size = [myTextString2 sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
size.height += 30.0f;
result = MAX(size.height, 44.0f);

My issue it that they return incorrect heights and I think it's the textSize where I use incorrect numbers. With long texts, the bottom part gets cut short (usually just a line with a few words), and for both CellStyles they have weird spacing above and below the text in the cell.

For UITableViewCellStyleValue2 I got the width size (207.0f) from making the text.backgroundColor red and then just calculating the size of the box. 300.0f width for UITableViewCellStyleDefault is how big the cell is with UITableViewStyleGrouped.

Does anyone know which values I need to use to properly calculate the size of an NSString and thereby get appropriate height for my cells?

Thanks

like image 887
runmad Avatar asked Jul 21 '09 18:07

runmad


2 Answers

Here is the code I am using for this. It works like a charm for one type of cell. It may have some useful parts for your application.

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
AppAppDelegate *appDelegate = (AppAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *Text = ([[appDelegate.myTextSectionsDelegateDict objectAtIndex:indexPath.section] objectForKey:@"Text"]);

    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [Text sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + 15;}
like image 170
Jonah Avatar answered Sep 18 '22 17:09

Jonah


When you create your cell, are you using the same font as the one you use to measure?

I used the tutorial on this page and everything worked for me. It might be useful to you too:

like image 45
rein Avatar answered Sep 21 '22 17:09

rein