Created
January 29, 2013 10:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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