iPhone – Wrap Text in UILabel

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.

1UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 20.0)];
2aLabel.adjustsFontSizetoWidth = YES; // This is a must
3aLabel.minimumFontSize = 8.0f;
4aLabel.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
02UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 64.0, 320.0, 60.0)];
03UIFont *aFont = [UIFont fontWithName:@"Helvetica" size:28.0];
04NSString *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
07for (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
19aLabel.font = aFont;
20aLabel.text = aText;
21aLabel.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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值