ZyusAn ZyusAn - 6 months ago 38
iOS Question

How to get exactly height of UILabel with line space?

I'm writing a expandable tableView header, I need to set the height of header accurately in tableView delegate method. I'm now using the following method to calculate the height of my header(a multi-line label):

CGRect calcuRect = [headerText boundingRectWithSize:CGSizeMake(myLabelWitdh, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:myLabelFont} context:nil];
CGFloat headerHeight = calcuRect.size.height;


However, I've found that the height calculated out is just about the text without include line space.
So how can I get the line space height of the label? or how to get accurate height of UILabel with line space?

Answer

You can get the exact height of UILabel with exactly passing the same font size and type and doing some calculations.
Here I used a UILabel with Helvetica font with font size 16.

Objective C

- (CGFloat)requiredHeight:(NSString*)labelText{

    UIFont *font = [UIFont fontWithName:@"Helvetica" size:16.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    label.text = labelText;
    [label sizeToFit];
    return label.frame.size.height;

}

Output

CGFloat size = [self requiredHeight:@"iOS Rocks"];
NSLog(@"%f",size);

size = [self requiredHeight:@"iOS Rocks\n"];
NSLog(@"%f",size);

Console Output

2016-04-10 01:37:46.812 testPro[6093:327503] 18.500000
2016-04-10 01:37:46.814 testPro[6093:327503] 37.000000

Swift

func requiredHeight(labelText:String) -> CGFloat {

    let font = UIFont(name: "Helvetica", size: 16.0)
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.font = font
    label.text = labelText
    label.sizeToFit()
    return label.frame.height

}