IOS开发

sizeToFit 和 sizeThatFits 区别

2020-07-11  本文已影响0人  Sharif_su

sizeToFit:

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

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)];
[label setBackgroundColor:[UIColor grayColor]];
[label setFont:[UIFont systemFontOfSize:20]];
label.text = @"宽高测试!!!";
[label sizeToFit];
NSLog(@"width=%.1f  height=%.1f ", label.frame.size.width, label.frame.size.height);
[self.view addSubview:label];

输入结果

[17002:605091] width=143.0  height=24.0

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

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)];
[label setBackgroundColor:[UIColor grayColor]];
[label setFont:[UIFont systemFontOfSize:20]];
label.text = @"宽高测试!!!";
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];
 test_su[17073:608773] sizeThatFits: width=143  height=24.0
 test_su[17073:608773] width=0.0  height=0.

总结:

sizeToFit:直接改变了这个label的宽和高,使它根据上面字符串的大小变化
sizeThatFits:会计算出最优的 size 但是不会改变 自己的 size
上一篇下一篇

猜你喜欢

热点阅读