这两个一般用于设置完label的text后重新计算label的size,以及更新frame让labelsize贴合text尺寸。
具体用法:
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 50, 20)];
testLabel.text = @"今天天气真不错,再过五天就放假啦啦啦啦啦啦啦啦!!";
testLabel.font = [UIFont systemFontOfSize:14];
testLabel.textAlignment=NSTextAlignmentCenter;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];
testLabel.textColor=[UIColor blackColor];
testLabel.backgroundColor=[UIColor blueColor];
[self.view addSubview:testLabel];
直接使用sizetofit,计算的label尺寸是以你初始设置的width为宽,适配高度。
效果如下:可以看出来宽度还是50 只是高度重新计算了。
如果用sizethatfit:
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 50, 20)];
testLabel.text = @"今天天气真不错,再过五天就放假啦啦啦啦啦啦啦啦!!!";
testLabel.font = [UIFont systemFontOfSize:14];
testLabel.textAlignment=NSTextAlignmentCenter;
testLabel.numberOfLines = 0;
//使用sizeThatFit计算lable大小
CGSize sizeThatFit = [testLabel sizeThatFits:CGSizeMake(150, 0)];
testLabel.frame = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, sizeThatFit.width + 8, sizeThatFit.height);
testLabel.textColor=[UIColor blackColor];
testLabel.backgroundColor=[UIColor yellowColor];
[self.view addSubview:testLabel];
使用sizethatfit计算label设置text的宽高时可以灵活设置你想固定的一个尺寸纬度,
比如我上面可以固定width = 150,计算高度。
算好之后要重新设置frame,可以给宽度再计算加上几pt使他左右有一定间隔。
效果如下:
上面testlabel的宽度就是按你设置的定宽150,然后计算的高度。 这里注意一下,如果你设置的定宽>实际计算出来的宽度,最终sizetofit计算出来的宽度
还是会以实际宽度为准。也就是会设置的定宽和实际宽度里的更小值为最终宽度。