美文网首页iOS
sizeToFit 和 sizeThatFits的使用区别

sizeToFit 和 sizeThatFits的使用区别

作者: Kevin追梦先生 | 来源:发表于2017-03-18 14:14 被阅读260次

首先我们可以看看苹果官方对这两个方法的解释:

// return 'best' size to fit given size.

does not actually resize view. Default is return existing view size

- (CGSize)sizeThatFits:(CGSize)size;

// calls sizeThatFits: with current view bounds and changes bounds size.

- (void)sizeToFit;

sizeToFit:会计算出最优的 size 而且会改变自己的size

sizeThatFits:会计算出最优的 size 但是不会改变 自己的 size

具体看下面的小例子:

sizeToFit

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)];

[label setBackgroundColor:[UIColor grayColor]];

[label setFont:[UIFont systemFontOfSize:20]];

label.text = @"北京欢饮您!!!";

//sizeToFit:直接改变了这个label的宽和高,使它根据上面字符串的大小做合适的改变

[label sizeToFit];

NSLog(@"width=%.1f  height=%.1f ", label.frame.size.width, label.frame.size.height);

[self.view addSubview:label];

输出结果:width=163.5 height=24.0

sizeThatFits

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)];

[label setBackgroundColor:[UIColor grayColor]];

[label setFont:[UIFont systemFontOfSize:20]];

label.text = @"北京欢饮您!!!";

//sizeThatFits并没有改变原始label的大小

CGSize sizeThatFits = [label sizeThatFits:CGSizeZero];

NSLog(@"sizeThatFits: width=%.1f  height=%.1f", sizeThatFits.width, sizeThatFits.height);

NSLog(@"width=%.1f  height=%.1f", label.frame.size.width, label.frame.size.height);

[self.view addSubview:label];

输出结果:

2017-03-08 11:34:02.455 joke[2272:116621] sizeThatFits: width=163.5  height=24.0

2017-03-08 11:34:02.455 joke[2272:116621] width=0.0  height=0.0

通过上面的两个小例子,我们可以验证出上面的结论:

sizeToFit:会计算出最优的 size 而且会改变自己的size

sizeThatFits:会计算出最优的 size 但是不会改变 自己的 size

相关文章

网友评论

  • dominghao:sizeThatFits:方法传入的参数CGSizeZero是指什么意思? //return 'best' size to fit given size.
    这里你给出的givenSize是zero. 参考的size是zero?
    我的理解:return 'best' size to fit given size.根据给出的size,计算出最优的size,这里的given Size可以看成一个参考范围.但是这个方法仅仅是返回最优的size.并没有改变自身的大小. 当使用sizeToFit的时候.(calls sizeThatFits: with current view bounds and changes bounds size.) 相当于调用sizeThatFits:并且传入自身的bounds作为参数. 然后把返回结果设为自身的size...

本文标题:sizeToFit 和 sizeThatFits的使用区别

本文链接:https://www.haomeiwen.com/subject/cvbunttx.html