ios UIView sizeToFit sizeThatFits

  UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 0, 0)];
    testLabel.backgroundColor = [UIColor whiteColor];
    testLabel.text = @"我们都有一个家啊,名字叫中国,家里攀着两条龙";
    testLabel.font = [UIFont systemFontOfSize:20];
    testLabel.textColor = [UIColor blackColor];

    [testLabel sizeThatFits:CGSizeMake(20, 20)];//会计算出最优的 size 但是不会改变 自己的 size,个人认为这个就是 label 自适应大小有用别的没什么用
    NSLog(@"testLabel sizeThatFits frame = %@", NSStringFromCGRect(testLabel.frame));
    NSLog(@"best size = %@",NSStringFromCGSize([testLabel sizeThatFits:CGSizeMake(20, 20)]));
    [testLabel sizeToFit];//会计算出最优的 size 而且会改变自己的size
    NSLog(@"testLabel sizeToFit frame = %@",NSStringFromCGRect(testLabel.frame));
[self.view addSubview:testLabel];
 
原文地址:https://www.cnblogs.com/shidaying/p/3981501.html