iPhone – Wrap Text in UILabel
In UILabel , there is an adjustsFontSizeToFitWidth property which will automatically adjust the text font size to fit the UILabel width.
1
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 20.0)];
2
aLabel.adjustsFontSizetoWidth =
YES
;
3
aLabel.minimumFontSize = 8.0f;
4
aLabel.numberOfLines = 1;
But this only work for numberOfLines = 1 …
Luckily, i found a workaround from a blog post . Here comes to the solution.
02
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 64.0, 320.0, 60.0)];
03
UIFont *aFont = [UIFont fontWithName:
@"Helvetica"
size:28.0];
04
NSString
*aText =
@"And I will love you, baby - Always. And I'll be there forever and a day - Always. I'll be there till the stars don't shine. Till the heavens burst and the words don't rhyme. And I know when I die, you'll be on my mind. And I'll love you - Always."
;
07
for
(
NSInteger
i = 28; i > 8; i--) {
08
aFont = [aFont fontWithSize:i];
10
CGSize constraintSize = CGSizeMake(320.0f, MAXFLOAT);
11
CGSize labelSize = [aText sizeWithFont:aFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
13
if
(labelSize.height <= 60.0f) {
21
aLabel.numberOfLines = 4;
24
[
self
.view addSubview:aLabel];
From: http://ykyuen.wordpress.com/2010/07/03/iphone-wrap-text-in-uilabel/