UILabel自适应高度

    UILabel *bodytext = [[UILabel alloc]init];
    bodytext.frame = CGRectMake(100,100, 310, 120);
    bodytext.textAlignment = NSTextAlignmentLeft;
    bodytext.font = [UIFont fontWithName:@"FZLanTingHei-L-GBK" size:15.0];
    bodytext.backgroundColor = [UIColor yellowColor];
    bodytext.textColor = [UIColor colorWithRed:(114.0/255.0) green:(115.0/255.0) blue:(116.0/255.0) alpha:1.0];
    bodytext.text = @"这是个测试,不信你试试!这是个测试,再不信你copy代码!这是个测试,果然!自适应高度了!";
    //自适应UILabel高度

    下面是关键
    bodytext.lineBreakMode = NSLineBreakByWordWrapping; //这个是关键
    bodytext.numberOfLines = 0;  //这个是关键
    CGSize size = [bodytext.text sizeWithFont:NULL constrainedToSize:CGSizeMake(310.0f,CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    CGRect newFrame = bodytext.frame;
    newFrame.size.height = size.height;
    bodytext.frame = newFrame;
    [bodytext sizeToFit];
    [self.view addSubview:bodytext];


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