ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit

转自:http://blog.csdn.net/senyangs/article/details/21078611

1.定义一个UILable 


[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. self.view.backgroundColor =[UIColor whiteColor];  
  2. NSString *str=@"目前支持以下站点";  
  3. UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  4. //文本文字自适应大小  
  5. notice.adjustsFontSizeToFitWidth = YES;  
  6. notice.text=str;  
  7. notice.textAlignment=NSTextAlignmentCenter;  
  8. CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];  
  9.  notice.center = CGPointMake(self.view.bounds.size.width/220) ;  
  10. notice.textColor=[UIColor whiteColor];  
  11. notice.backgroundColor=[UIColor blackColor];  
  12. [self.view addSubview:notice];  

得到的效果如下图

自适应大小ios7以后有两种可行的方案:

1.sizeThatFits

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSString *str=@"目前支持以下站点";  
  2.  UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  3.  //文本文字自适应大小  
  4.  notice.adjustsFontSizeToFitWidth = YES;  
  5.  notice.text=str;  
  6.  notice.textAlignment=NSTextAlignmentCenter;  
  7.  //使用sizeThatFit计算lable大小  
  8.  CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];  
  9.  //重新指定frame  
  10.  notice.frame=CGRectMake(00, sizeThatFit.width, sizeThatFit.height);  
  11.  notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;  
  12.  notice.textColor=[UIColor whiteColor];  
  13.  notice.backgroundColor=[UIColor blackColor];  
  14.  [self.view addSubview:notice];  

效果图:

2.sizeToFit

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSString *str=@"目前支持以下站点";  
  2. UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  3. //文本文字自适应大小  
  4. notice.adjustsFontSizeToFitWidth = YES;  
  5. notice.text=str;  
  6. notice.textAlignment=NSTextAlignmentCenter;  
  7. [notice sizeToFit];//使用sizeToFit  
  8. notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;  
  9. notice.textColor=[UIColor whiteColor];  
  10. notice.backgroundColor=[UIColor blackColor];  
  11. [self.view addSubview:notice];  


效果图:

注意:1.计算lable大小的时候需要先进行lable的text赋值

    2.如果要将lable居中显示的话,lable.center属性的设置必须放在设置新大小之后,不然会出现不居中的情况

    3.ios7之前还有其他的方法

cgSize=[str sizeWithFont:font];

这个方法是NSString的方法,听说在ios7下使用会计算不准确

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值