简体   繁体   中英

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

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;

}

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