现在的位置: 首页 > 综合 > 正文

iPhone – Wrap Text in UILabel

2017年10月31日 ⁄ 综合 ⁄ 共 1523字 ⁄ 字号 评论关闭

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; // This is a must
3 aLabel.minimumFontSize = 8.0f;
4 aLabel.numberOfLines = 1; // This is a must too =.=

But this only work for numberOfLines = 1
 

Luckily, i found a workaround from a blog post. Here comes to the solution.

01 // Initialize the Label, Text and Font
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.";
05  
06 // Logic for adjusting the size
07 for (NSInteger i = 28; i > 8; i--) {
08     aFont = [aFont fontWithSize:i];
09     // Limit the width to UILabel width
10     CGSize constraintSize = CGSizeMake(320.0f, MAXFLOAT);
11     CGSize labelSize = [aText sizeWithFont:aFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
12     // Break the loop when text height < UILabel height
13     if (labelSize.height <= 60.0f) {
14         break;
15     }
16 }
17  
18 // Set the font and text for UILabel
19 aLabel.font = aFont;
20 aLabel.text = aText;
21 aLabel.numberOfLines = 4;
22  
23 // Add the Label to the view and release it
24 [self.view addSubview:aLabel];
25 [aLabel release];

From:  http://ykyuen.wordpress.com/2010/07/03/iphone-wrap-text-in-uilabel/

抱歉!评论已关闭.