iOS技术篇:sizeToFit 和 sizeThatFits 区别
sizeToFit
:会计算出最优的 size 而且会改变自己的size
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 0, 0)]; [label setBackgroundColor:[UIColor grayColor]]; [label setFont:[UIFont systemFontOfSize:20]]; label.text = @"北京欢迎您!!!"; //sizeToFit:直接改变了这个label的宽和高,使它根据上面字符串的大小做合适的改变 [label sizeToFit]; NSLog(@"width=%.1f height=%.1f ", label.frame.size.width, label.frame.size.height); [self.view addSubview:label];
输出结果:
width=163.5 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 = @"北京欢迎您!!!"; //sizeThatFits并没有改变原始label的大小 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];
输出结果:
sizeThatFits: width=163.5 height=24.0
width=0.0 height=0.0