首先我們可以看看蘋果官方對這兩個方法的解釋:
// 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
:會計算出最優(yōu)的 size 而且會改變自己的size
sizeThatFits
:會計算出最優(yōu)的 size 但是不會改變 自己的 size
具體看下面的小例子:
sizeToFit
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)];
[label setBackgroundColor:[UIColor grayColor]];
[label setFont:[UIFont systemFontOfSize:20]];
label.text = @"北京歡飲您!F惫恕休吠!";
//sizeToFit:直接改變了這個label的寬和高印荔,使它根據(jù)上面字符串的大小做合適的改變
[label sizeToFit];
NSLog(@"width=%.1f height=%.1f ", label.frame.size.width, label.frame.size.height);
[self.view addSubview:label];
輸出結(jié)果: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 = @"北京歡飲您Vマ薄@们佟误堡!";
//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];
輸出結(jié)果:
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
通過上面的兩個小例子铆农,我們可以驗證出上面的結(jié)論:
sizeToFit
:會計算出最優(yōu)的 size 而且會改變自己的size
sizeThatFits
:會計算出最優(yōu)的 size 但是不會改變 自己的 size