让label自适应里面的文字,自动调整宽度和高度的

UILabel * testlable = [[UILabel alloc]initWithFrame:CGRectMake(10,20,200,20)];
    
    NSString * tstring =@"UILabel  ios7 与ios7之前实现自适应撑高的方法,文本的内容长度不一,我们需要根据内容的多少来自动换行处理。在IOS7下要求font,与breakmode与之前设置的完全一致sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping";
    
    testlable.numberOfLines =2;
    
    UIFont * tfont = [UIFont systemFontOfSize:14];
    
    testlable.font = tfont;
    
    testlable.lineBreakMode =NSLineBreakByTruncatingTail ;
    
    testlable.text = tstring ;
    [testlable setBackgroundColor:[UIColor redColor]];
    
    [self.view addSubview:testlable];
    
    //高度估计文本大概要显示几行,宽度根据需求自己定义。 MAXFLOAT 可以算出具体要多高
    
    CGSize size =CGSizeMake(300,60);
    
    // label可设置的最大高度和宽度
    //    CGSize size = CGSizeMake(300.f, MAXFLOAT);

    //    获取当前文本的属性
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    
    //ios7方法,获取文本需要的size,限制宽度
    
    CGSize  actualsize =[tstring boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    
    // ios7之前使用方法获取文本需要的size,7.0已弃用下面的方法。此方法要求font,与breakmode与之前设置的完全一致
    //    CGSize actualsize = [tstring sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
    //   更新UILabel的frame
    
    
    testlable.frame =CGRectMake(10,20, actualsize.width, actualsize.height);

 该方法有时候会显示的不准确

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentif = @"重用池";
    AdaptiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentif];
    if (!cell) {
        cell = [[AdaptiveTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentif];
    }
    if ([self.connectArray count] == 0) {
        [cell.titleLabel setText:@"哎呀~没有找到你要看的,搜搜别的吧~"];
        [cell.titleLabel setTextAlignment:NSTextAlignmentCenter];
    } else {
        NSDictionary *dicCon = [self.connectArray objectAtIndex:indexPath.row];
        NSString *titleText = [dicCon objectForKey:@"title"];
        //自适应  此处高亮!
        cell.titleLabel.numberOfLines = 0;
        CGFloat height = ([titleText length]/15)*20 + 30;
        [cell.titleLabel setFrame:CGRectMake(5, 0, 310, height)];
        [cell.titleLabel setText:titleText];
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell的高自适应 此处高亮! NSDictionary *dicCon = [self.connectArray objectAtIndex:indexPath.row]; NSString *titleText = [dicCon objectForKey:@"title"]; CGFloat height = ([titleText length]/15)*20 + 30; return height; }
原文地址:https://www.cnblogs.com/lxllanou/p/3741898.html