Skip to content

Instantly share code, notes, and snippets.

@boztalay
Created January 29, 2013 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boztalay/4663429 to your computer and use it in GitHub Desktop.
Save boztalay/4663429 to your computer and use it in GitHub Desktop.
Vertically and horizontally centering the contents of a UILabel, with dynamic text and font size, within a given CGRect. This can be used, for example, to draw numbers within a container, like a small circle, since the size of the text of a number is difficult to predict.
//Note, this should probably be handled in a different way in production code
#define MIN_FONT_SIZE 3.25f
- (void)label:(UILabel*)label setText:(NSString*)text andCenterInRect:(CGRect)rect {
label.text = [NSString stringWithFormat:@"%d", indicatorNumber];
CGFloat fontSizeOfContents;
[label.text sizeWithFont:label.font
minFontSize:MIN_FONT_SIZE
actualFontSize:&fontSizeOfContents
forWidth:rect.size.width
lineBreakMode:NSLineBreakByWordWrapping];
label.font = [UIFont systemFontOfSize:fontSizeOfContents];
[label sizeToFit];
label.center = CGPointMake(rect.size.width / 2.0f, rect.size.height / 2.0f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment