sizeThatFits and sizeToFit是UIView的两个方法, 官方文档上说:
- (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.
UIView *view = [[UIViewalloc] initWithFrame:CGRectMake(100,100, 200,100)];
view.backgroundColor = [UIColoryellowColor];
UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(5,5, 0,0)];
[label setFont:[UIFontsystemFontOfSize:20]];
label.text =@"hello wdszgrf";
CGSize sizeThatFits = [labelsizeThatFits:CGSizeZero];
NSLog(@"---- %f %f ----", sizeThatFits.width, sizeThatFits.height);
// output: ---- 117.000000 24.000000 ----
NSLog(@"**** %f %f ****", label.frame.size.width, label.frame.size.height);
// output: **** 0.000000 0.000000 ****说明sizeThatSize并没有改变原始label的大小
[label sizeToFit]; // 这样搞就直接改变了这个label的宽和高,使它根据上面字符串的大小做合适的改变
[label setCenter:CGPointMake(80,50)];
NSLog(@"==== %f %f ====", label.frame.size.width, label.frame.size.height);
// output: ==== 117.000000 24.000000 ====
[view addSubview:label];
[self.viewaddSubview:view];
// UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
// notice.text=@"目前支持以下站点";
// notice.textColor=[UIColor whiteColor];
// notice.backgroundColor=[UIColor blackColor];
// notice.adjustsFontSizeToFitWidth = YES;
// notice.textAlignment=NSTextAlignmentCenter;
//
// //使用sizeThatFit计算lable大小
// CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];
// //重新指定frame
// notice.frame=CGRectMake(0, 0, sizeThatFit.width, sizeThatFit.height);
// //以上两行代码等价于[notice sizeToFit];//使用sizeToFit
//
// notice.center = CGPointMake(self.view.bounds.size.width/2, 20) ;
// [self.view addSubview:notice];