首先我们可以看看苹果官方对这两个方法的解释:
// 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