OC学习40:sizeToFit和sizeThatFit
前言
通过官方文档查看两个方法的区别:
1 2 3 4 5 6 7
| - (CGSize)sizeThatFits:(CGSize)size;
return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (void)sizeToFit;
calls sizeThatFits: with current view bounds and changes bounds size.
|
不换行情况下
下面通过代码来验证一下,不换行情况下的区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #pragma mark -不换行 - (void)NoWarp{ UILabel * titleL = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 100, 18)]; titleL.text = @"我是谁?我是张建,欢迎来到我的世界!"; titleL.textColor = [UIColor redColor]; titleL.backgroundColor = [UIColor yellowColor]; [self.view addSubview:titleL]; // sizeThatFits: 会计算出最优的 size 但是不会改变 自己的 size CGSize size = [titleL sizeThatFits:CGSizeMake(150, MAXFLOAT)]; NSLog(@"w:%f h:%f",size.width,size.height); // sizeToFit: 会计算出最优的 size 而且会改变自己的 size [titleL sizeToFit]; NSLog(@"w:%f h:%f",titleL.frame.size.width,titleL.frame.size.height); }
|
查看代码的结果:
1 2
| 2021-10-09 16:34:44.011176+0800 sizeToFit和sizeThatFit[506:157387] w:308.000000 h:20.500000 2021-10-09 16:34:44.011280+0800 sizeToFit和sizeThatFit[506:157387] w:308.000000 h:20.500000
|
显示的效果:
换行的情况下
下面用代码来验证一下,换行的情况下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #pragma mark -换行 - (void)warp{ UILabel * titleL = [[UILabel alloc] initWithFrame:CGRectMake(10, 200, 300, 18)]; titleL.text = @"我是谁?我是张建,欢迎来到我的世界!,我是谁?我是张建,欢迎来到我的世界!,我是谁?我是张建,欢迎来到我的世界!,我是谁?我是张建,欢迎来到我的世界!,我是谁?我是张建,欢迎来到我的世界!"; titleL.textColor = [UIColor redColor]; titleL.backgroundColor = [UIColor yellowColor]; titleL.numberOfLines = 0; [self.view addSubview:titleL]; // sizeThatFits: 会计算出最优的 size 但是不会改变 自己的 size CGSize size = [titleL sizeThatFits:CGSizeMake(300, MAXFLOAT)]; NSLog(@"w:%f h:%f",size.width,size.height); // sizeToFit: 会计算出最优的 size 而且会改变自己的 size [titleL sizeToFit]; NSLog(@"w:%f h:%f",titleL.frame.size.width,titleL.frame.size.height); }
|
查看代码运行结果:
1 2
| 2021-10-09 16:39:54.036423+0800 sizeToFit和sizeThatFit[7271:250369] w:299.333333 h:122.000000 2021-10-09 16:39:54.036707+0800 sizeToFit和sizeThatFit[7271:250369] w:299.333333 h:122.000000
|
- Post title:OC学习40:sizeToFit和sizeThatFit
- Post author:张建
- Create time:2023-04-23 14:29:21
-
Post link:https://redefine.ohevan.com/2023/04/23/OC/OC学习40:sizeToFit和sizeThatFit/
-
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.