Pheepster
Pheepster

Reputation: 6347

Setting dynamic UILabel Height

I have an app with a table view that needs to support dynamic cell heights. In the cell's layoutSubviews method, I am generating a frame for my UILabel controls, which are the only dynamic sized controls in the cells.

For some reason, the width being returned from the following method is less than what it should be and the text gets truncated, but only on short text, such as one word. The width should be maintained as the width that is passed in as the initial frame.

That said, what my method needs to accomplish is adjusting the size of the label to fit all the text while maintaining a preset width.

Here's the code I am using:

- (CGRect)getLabelSizeForText:(NSString*)text withInitialRect:(CGRect)labelFrame andFontSize:(CGFloat)fontSize{
    CGSize constrainedSize = CGSizeMake(labelFrame.size.width, MAXFLOAT);
    NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize], NSFontAttributeName, nil];
    CGSize requiredSize = [text boundingRectWithSize:constrainedSize
                                             options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                          attributes:attributesDict context:nil].size;

    CGRect adjustedFrameRect = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, requiredSize.width, requiredSize.height);

    return adjustedFrameRect;
}

Upvotes: 0

Views: 145

Answers (1)

Christian
Christian

Reputation: 382

This works for me,

+ (CGSize)textSizeForText:(NSString *)text {

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat width = screenWidth - kPaddingRight;
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 2.5;
NSDictionary *dict = @{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName: [UIFont systemFontOfSize:15] };
[attributedString addAttributes:dict range:NSMakeRange(0, text.length)];

CGRect paragraphRect = [attributedString boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];


return paragraphRect.size;

}

Upvotes: 1

Related Questions