Skip to content

Instantly share code, notes, and snippets.

@brcimo
Forked from danielphillips/UILabel+dynamicSizeMe.h
Created August 14, 2012 20:28
Show Gist options
  • Save brcimo/3352600 to your computer and use it in GitHub Desktop.
Save brcimo/3352600 to your computer and use it in GitHub Desktop.
Adjust UILabel to change it's frame according to it's content
@interface UILabel (dynamicSizeMe)
-(float)resizeToFit;
-(float)expectedHeight;
-(void)resizeToStretch;
-(float)expectedWidth;
@end
#import "UILabel+dynamicSizeMe.h"
@implementation UILabel (dynamicSizeMe)
-(float)resizeToFit
{
float height = [self expectedHeight];
CGRect newFrame = [self frame];
newFrame.size.height = height;
[self setFrame:newFrame];
return newFrame.origin.y + newFrame.size.height;
}
-(float)expectedHeight
{
[self setNumberOfLines:0];
[self setLineBreakMode:UILineBreakModeWordWrap];
CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,9999);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.height;
}
-(void)resizeToStretch
{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
-(float)expectedWidth
{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(9999,self.frame.size.height);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
@end
@brcimo
Copy link
Author

brcimo commented Aug 14, 2012

Added: resizeToStretch to adjust the width of the label based on the text size.

You can now adjust the label height and width automatically based on the text.

Found in a post on stackoverflow by danielphillips

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