heightForRowAtIndexPath for longer NSStrings

时间秒杀一切 提交于 2019-11-30 07:24:49

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;}

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:

It seeems you've figured out that you were using the wrong text size. You might want to just use the font and lineBreakMode properties of the label to avoid this problem in the future, especially if you change them in the cell at a later time. Also, for readability's sake, I would avoid adding to the height before returning a number. Instead I'd try something like this:

CGSize textSize = CGSizeMake( 300.0, 1979 );
CGSize size = [ myTextString1 sizeWithFont:[[ cell textLabel ] font ]
                         constrainedToSize:textSize
                             lineBreakMode:[[ cell textLabel ] lineBreakMode ]];

result = MAX( size.height + 30, 44.0f );

I used 1979 because according to the documentation, one should not return values larger than 2009.

Valerio Mazzeo

If you want to calculate the height properly for cellvalue2 you should use: [UIFont boldSystemFontOfSize:15.0f] and as linebreakmode: NSLineBreakByTruncatingTail

If you don't use bold, the text will fill correctly but you will lose the correct vertical padding.

The rest of your calculation are correct.

When is working for me is to compute the constraintSize based on the width of the table view:

CGSize constraintSize = CGSizeMake(tableView.frame.size.width * 0.6, 2009);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
barryjones

Easiest way to do this:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

CGFloat result = 10.0f;
if(indexPath.section == 1) // here i compare the sections
{
    result = 400.0f;
}
return result;
}

Return the values based on the sections you have. This will give you custom row heights.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!