TechChain
TechChain

Reputation: 8944

How to calculate the size of label based on font size & text?

I have added a label on a view in my app.I have given it some size font size as 16.0.When the text in label is small then it works fine.But when the text is more in label i want label to increase it's height automatically & also update the constraints.So that i don't want any constraints related warnings.What is the best way of doing it? Edit

    cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping;
    cell.label_like_count.numberOfLines = 0;
    [cell.label_like_count sizeToFit];
    NSString *first_like_user=@"Some Name";
    int count=[first_like_user length];
    NSString *like_count=@"12";
    like_count=[like_count stringByAppendingString:@" others like your post"];
    first_like_user=[first_like_user stringByAppendingString:@" and "];
    first_like_user=[first_like_user stringByAppendingString:like_count];
    NSMutableAttributedString *mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];

    NSAttributedString *attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];

    [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];

    [mutableAttributeStr appendAttributedString:attributeStr];

I tried below code

  CGSize maximumLabelSize = CGSizeMake(296,9999);

    CGSize expectedLabelSize = [first_like_user sizeWithFont:cell.label_like_count.font
                                      constrainedToSize:maximumLabelSize
                                          lineBreakMode:cell.label_like_count.lineBreakMode];

    //adjust the label the the new height.
    CGRect newFrame = cell.label_like_count.frame;
    newFrame.size.height = expectedLabelSize.height;
    cell.label_like_count.frame = newFrame;

    [cell.label_like_count setAttributedText:mutableAttributeStr];

But this does not increase the label height & label does not come into multilines?

Upvotes: 0

Views: 211

Answers (2)

NixSolutionsMobile
NixSolutionsMobile

Reputation: 191

I can recommend to add very useful pod to your project: pod 'UpdateAutoLayoutConstraints'

In your file import necessary headers:

#import "UIView+UpdateAutoLayoutConstraints.h"

[label setText:@"some long text"];
CGFloat newHeight = [label sizeThatFits:CGSizeMake(expectedWidth, 99999999)].height;    
[label setConstraintConstant:newHeight forAttribute:NSLayoutAttributeHeight];

Upvotes: 1

Tamás Zahola
Tamás Zahola

Reputation: 9321

Unless you specify an explicit height constraint, UILabels calculate their height constraints automatically via intrinsicContentSize. All you have to do is to determine the label's width (via an explicit width constraint or through left/right edge constraints), and it'll adjust its height based on the content.

Upvotes: 1

Related Questions