sizeThatFits and sizeToFit

来源:互联网 发布:java时间转化为毫秒 编辑:程序博客网 时间:2024/06/05 02:16

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

 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,只会计算出文本的size2.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