UILabel 自适应高度

总的方法还是:

NSString UIKit Additions Reference

sizeWithFont:constrainedToSize:lineBreakMode:

第一种方法:

   

UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
   NSString *text = @"First take clear picture and then try to zoom in to fit the ";
   instructions.text = text;
   instructions.lineBreakMode = UILineBreakModeWordWrap; //这个是关键
   instructions.numberOfLines = 0;  //这个是关键  
  [instructions setTextColor:[UIColor grayColor]];  
   CGSize maximumSize = CGSizeMake(300, CGFLOAT_MAX); // 第一个参数是label的宽度,第二个参数是固定的宏定义,CGFLOAT_MAX
   CGSize expectedLabelSize = [text sizeWithFont:instructions.font 
                                constrainedToSize:maximumSize 
                                    lineBreakMode:UILineBreakModeWordWrap];

    CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    [instructions sizeToFit];
    [self addSubview:instructions];

第二种方法:

 UILabel *instructions=[[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
        NSString *text = @"First take clear picture and then try to zoom in to fit the ";
         instructions.text = text;
        instructions.lineBreakMode = UILineBreakModeWordWrap; //这个是关键
        instructions.numberOfLines = 0;  //这个是关键
       [instructions setTextColor:[UIColor grayColor]];  
      CGSize size = [instructions.text sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:CGSizeMake(300.0f,CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
       CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    [instructions sizeToFit];
    [self addSubview:instructions];


你可能感兴趣的:(UILabel 自适应高度)