sizeThatFits and sizeToFit

其两者的区别,通过一个小例子便可看出:

 NSString *str=@"目前支持以下站点";
    UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(20, 100, 200, 20)];
    //文本文字自适应大小
    notice.font = [UIFont systemFontOfSize:14];
    notice.text=str;
    notice.textAlignment=NSTextAlignmentCenter;
    //使用sizeThatFit计算lable大小
    CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];
    //重新指定frame
    NSLog(@"---- %f  %f ----", sizeThatFit.width, sizeThatFit.height);
    NSLog(@"**** %f  %f ****", notice.frame.size.width, notice.frame.size.height);
    NSLog(@"------------------------------------------");

    [notice sizeToFit];
    NSLog(@"**** %f  %f ****", notice.frame.size.width, notice.frame.size.height);
    notice.textColor=[UIColor whiteColor];
    notice.backgroundColor=[UIColor blackColor];
    [self.view addSubview:notice];

以上输出结果:

2016-12-30 10:18:51.866 UI部分[7490:87265] ---- 114.500000  17.000000 ----
2016-12-30 10:18:51.871 UI部分[7490:87265] **** 200.000000  20.000000 ****
2016-12-30 10:18:51.872 UI部分[7490:87265] ------------------------------------------
2016-12-30 10:18:51.872 UI部分[7490:87265] **** 114.500000  17.000000 ****

从以上输出结果可以看出

1.sizeThatFits并没有改变label的frame,只会计算出文本的size
2.sizeToFit会改变这个label的宽和高,使它根据上面字符串的大小做合适的改变

进一步比较:

- (void)sizeToFits2
{
    NSString *str=@"sizeToFits2目前支持以下站点sizeToFits2,sizeToFits2目前支持以下站点sizeToFits2,sizeToFits2目前支持以下站点sizeToFits2";
    UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(20, 300, 200, 20)];
    //文本文字自适应大小
    notice.font          = [UIFont systemFontOfSize:14];
    notice.text          =str;
    notice.numberOfLines = 0;
    [notice sizeToFit];
    notice.textColor     =[UIColor whiteColor];
    notice.backgroundColor=[UIColor blackColor];
    [self.view addSubview:notice];

}


- (void)sizeThatFits2
{
    NSString *str=@"sizeThatFits2目前支持以下站点sizeThatFits2.sizeThatFits2目前支持以下站点sizeThatFits2,sizeThatFits2目前支持以下站点sizeThatFits2";
    UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(20, 100, 200, 20)];
    //文本文字自适应大小
    notice.font          = [UIFont systemFontOfSize:14];
    notice.text          =str;
    notice.numberOfLines = 0;
    CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];
    notice.frame         = CGRectMake(notice.frame.origin.x, notice.frame.origin.y, sizeThatFit.width, sizeThatFit.height);
    notice.textColor     =[UIColor whiteColor];
    notice.backgroundColor=[UIColor blackColor];
    [self.view addSubview:notice];

}

这里写图片描述

对比:
1、当不设置多行时,两者并没有什么差别。
2、当文字较多时,设置numberOfLines = 0,效果如上图所示,sizeThatFits并不会折行显示,sizeToFits会在设置的宽度内这行显示。

因此,处理但行文本操作时两者都可以,多行时使用sizeToFits可以完成。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值