简体   繁体   中英

how to calculate accurate height of a label if it contains text with more spaces in iOS?

I just finding how to calculate exact height of label. I read same questions but my problem is different regarding the height of label. Following code I am using for calculating dynamic height of cell depending upon the label height.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        CGSize size;
        Comment *objCommnt = [arrOfComments objectAtIndex:indexPath.row];
        NSString *msg = objCommnt.comment;

        CGSize textSize = { 260.0, 10000.0 };
        size = [msg sizeWithFont:[UIFont boldSystemFontOfSize:12]
               constrainedToSize:textSize
                   lineBreakMode:UILineBreakModeWordWrap];
        size.height += padding;
        return size.height+padding +5;

        return 100;
}

where padding is

      static CGFloat padding = 20.0;

For commennts having proper spacing it gives me correct size and it works find as show in below image: 在此处输入图片说明

For comments having text with continuous word means having huge space between two word gives me woring height as show in image below 在此处输入图片说明

I second image you can see what is my issue. What I am done for checking how much height required for that same lable checked in nib file by putting labels it's 92 when i am calulating its height dynamic its calculted as 80 why is it so ?? I think its due to more spacing between two words or longer word then space after it Any body has any idea why is it like that any help will be appreciated. Thank you.

您已将标签宽度设置为260px,但这是表视图中标签的实际宽度吗?

Calculate the height is easy, enjoy:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{   
    Comment *objCommnt = [arrOfComments objectAtIndex:indexPath.row];
    NSString *cellText = objCommnt.comment;
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
    CGSize constraintSize = CGSizeMake(260.0, MAXFLOAT);

    CGSize labelSize = [cellText sizeWithFont:cellFont 
                            constrainedToSize:constraintSize 
                                lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20.0f;
}

Hope it will help!

UPDATE!!! You only need:

return size.height+padding +5;

Instead of:

return size.height+padding +5;

        return 100;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM