UITableView cell中label自动换行和自定义label自动换行

换行的前提必须是有足够的高度 才能换 否则不显示超出部分 

所以,在设置label换行的时候 要考虑cell的高度,cell的高度也要变化,废话不多说,来段代码:

cell.label.text=[dict objectForKey:@"info"];
    cell.label.numberOfLines=0;  //可多行显示
    cell.label.lineBreakMode=NSLineBreakByWordWrapping;//拆行
设置label的高度
[self changeLabelHeight:cell.label :cell.label.text]; 

//设置label的高度
-(void)changeLabelHeight:(UILabel *)label : (NSString *)string{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
    //计算UILabel字符显示的实际大小
     size=[string boundingRectWithSize:CGSizeMake(145, 1000)//最大限制的宽和高
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attribute
                                          context:nil].size;
    //重设UILabel实例的frame
    [label setFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y, size.width, size.height)];
   
    NSLog(@"%lf",size.height);
}
//设置cell的高度
//设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
    NSDictionary *dict=[self.listData objectAtIndex:indexPath.row+1];
//获取数据,根据数据来确定长和高
   CGSize size=[[dict objectForKey:@"info"] boundingRectWithSize:CGSizeMake(156, 1000)//最大限制宽和高
                              options:NSStringDrawingUsesLineFragmentOrigin
                           attributes:attribute
                              context:nil].size;
        NSLog(@"row heigth :%lf",size.height+20);
    if (size.height+20<58) {
        return 58;
    }else{
       return size.height+20;
    }
}

原文地址:https://www.cnblogs.com/niit-soft-518/p/4026118.html