谈谈 sizeToFit 与 sizeThatFit

先看看苹果官方文档对这连个的方法的解释:学习

- (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.

意思是说,sizeThatFits: 会计算出最优的 size 可是不会改变 本身的 size,而 sizeToFit: 会计算出最优的 size 并且会改变本身的 size。那么二者的联系是什么呢?code

实际上,当调用 sizeToFit 后会调用 sizeThatFits 方法来计算 UIView 的 bounds.size 而后改变 frame.size。也就是说,其实咱们也能够不使用 [ label sizeToFit] 来计算 label 内容的 size ,首先调用 sizeThatFits 方法或者一个 CGSize 而后改变 label.frame.size 就能够获得 [label sizeToFit]同样的效果。下面用实例加以说明:blog

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
    testLabel.text = @"欢迎关注黄飞的csdn博客";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    //使用sizeThatFit计算lable大小
    CGSize sizeThatFit=[testLabel sizeThatFits:CGSizeZero];
    NSLog(@"%f-----%f", sizeThatFit.width, sizeThatFit.height);
    NSLog(@"%f-----%f", testLabel.frame.size.width, testLabel.frame.size.height);
    // 调用sizeToFit
    [testLabel sizeToFit];
    NSLog(@"%f-----%f", testLabel.frame.size.width, testLabel.frame.size.height);
    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

运行结果以下所示:
这里写图片描述图片

这也验证了官方的对其的解释:sizeThatFits: 会计算出最优的 size 可是不会改变 本身的 size,而 sizeToFit: 会计算出最优的 size 并且会改变本身的 size。文档

上述说的是 Label 单行显示时的情形,当 Label 文本较长以致于不能单行显示时,二者也是有区别的。博客

sizeThatFit:it

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 50, 20)];
    testLabel.text = @"欢迎关注黄飞的csdn博客,这里有你想要的东西,欢迎关注!!";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    testLabel.numberOfLines = 0;
    //使用sizeThatFit计算lable大小
    CGSize sizeThatFit = [testLabel sizeThatFits:CGSizeZero];
    testLabel.frame    = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, sizeThatFit.width, sizeThatFit.height);

    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

sizeToFit:class

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 100, 20)];
    testLabel.text = @"欢迎关注黄飞的csdn博客,这里有你想要的东西,欢迎关注!!";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    testLabel.numberOfLines = 0;

    [testLabel sizeToFit];

    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

二者的效果对好比下:
这里写图片描述test

当设置多行显示时,二者又体现出区别,sizeThatFits并不会折行显示,sizeToFits会在设置的宽度内这行显示。这实际上又从另外一方面验证了官方的解释。object

知其然,更要知其因此然,学习没有捷径,坚持和专研是硬道理,多分享则乐趣无穷!欢迎关注后续博文!

相关文章
相关标签/搜索