Skip to content

Instantly share code, notes, and snippets.

@danielphillips
Created March 22, 2011 16:10
Show Gist options
  • Save danielphillips/881486 to your computer and use it in GitHub Desktop.
Save danielphillips/881486 to your computer and use it in GitHub Desktop.
Allows you adjust a UILabel's height according to its content and retreive expected height for given input
@interface LabelSizer : NSObject {
}
+(float)getExpectedHeightForLabel:(UILabel*)label;
+(float)makeLabelCorrectSizeForCurrentWidth:(UILabel*)label;
+(float)getExpectedHeightForText:(NSString*)text withFontName:(NSString*)font atSize:(float)fontSize inContainerWidth:(float)width;
@end
#import "LabelSizer.h"
@implementation LabelSizer
+(float)getExpectedHeightForLabel:(UILabel*)label{
// Uses the incoming label's frame for width constraint
[label setNumberOfLines:0];
[label setLineBreakMode:UILineBreakModeWordWrap];
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width,9999);
CGSize expectedLabelSize = [[label text] sizeWithFont:[label font]
constrainedToSize:maximumLabelSize
lineBreakMode:[label lineBreakMode]];
return expectedLabelSize.height;
}
+(float)makeLabelCorrectSizeForCurrentWidth:(UILabel*)label{
float height = [self getExpectedHeightForLabel:label];
CGRect newFrame = [label frame];
newFrame.size.height = height;
[label setFrame:newFrame];
return newFrame.origin.y + newFrame.size.height;
}
+(float)getExpectedHeightForText:(NSString*)text withFontName:(NSString*)fontName atSize:(float)fontSize inContainerWidth:(float)width{
CGSize constraint = CGSizeMake(width, 9999);
CGSize size = [text sizeWithFont:[UIFont fontWithName:fontName size:fontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
return size.height;
}
@end
@danielphillips
Copy link
Author

+ getExpectedHeightForText:withFontName:atSize:inContainerWidth: is used in the context that you would need to know the height of a UILabel but not require one a UILabel to be instantiated, this can be the case when implementing - tableView:heightForRowAtIndexPath: for example to work out the correct height for a cell that has one or more UILabel objects with dynamic heights.

The two other methods can be assigned to a category, which is more logical, this gist has been created on the following link: https://gist.github.com/1005494

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment