Thursday, June 23, 2011

Dynamic UILabel - Calculate height of UILabel based on Content

Following will return a new Frame size based on a given UILabel and NSString.
Thought the code below is for a UILabel, it will also work for UITextview with just a few changes.

- (CGRect) dynamicFrameForUILabels:(UILabel*) theLabel withContent:(NSString*) theContent {
    CGSize maximumLabelSize = CGSizeMake(296,9999);
   
    CGSize expectedLabelSize = [theContent sizeWithFont:theLabel.font
                                      constrainedToSize:maximumLabelSize
                                          lineBreakMode:theLabel.lineBreakMode];
   
    CGRect newFrame = theLabel.frame;
    newFrame.size.height = expectedLabelSize.height;
    return newFrame;
}

No comments:

Post a Comment