泰州做兼职的网站/南京seo域名
Demo下载
在UITableView中要想cell自适应行高,其实就是UIlabel上的文本根据文本以及文本字体大(即boundingRectWithSize方法)来进行高度的调整,从而重新对cell上UIlabel下面的其他控件进行frame上的y的改变,达到cell上的布局调整,高度的自适应,代码如下:
在VC文件中
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{MessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageListCell"];if(!cell){cell = [[MessageListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageListCell"];cell.selectionStyle = UITableViewCellSelectionStyleNone;}if (arr_messlist.count > 0){if (indexPath.row < arr_messlist.count) {//显示cell数据NSString *str = arr_messlist[indexPath.row];[cell setByString:str];}}return cell;
}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{//获取当前行文本内容NSString *str = arr_messlist[indexPath.row];//自适应高度CGSize size = CGSizeMake(Wi - f_CalcRealWidthByiPhone6(10) * 2 - f_CalcRealWidthByiPhone6(5) * 2, 0);CGRect rect = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} context:nil];CGFloat messH = f_CalcRealHeightByiPhone6(20) + rect.size.height + f_CalcRealHeightByiPhone6(15);return f_CalcRealHeightByiPhone6(20) * 2 + messH;
}
在cell文件中
#pragma mark - 显示数据
- (void)setByString:(NSString *)string
{//1、自适应高度[self refreshHeight:string];//2、赋值lbl_time.text = @"2016-09-20";lbl_title.text = @"文本信息";lbl_content.text = string;
}- (void)refreshHeight:(NSString *)string
{//内容NSString *str = string;//自适应高度CGSize size = CGSizeMake(Wi - f_CalcRealWidthByiPhone6(10) * 2 - f_CalcRealWidthByiPhone6(5) * 2, 0);CGRect rect = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:FONT_S_14} context:nil];CGFloat messH = f_CalcRealHeightByiPhone6(25) + rect.size.height + f_CalcRealHeightByiPhone6(10);//信息背景v_mess.frame = CGRectMake(f_CalcRealWidthByiPhone6(10), f_CalcRealHeightByiPhone6(40), Wi - f_CalcRealWidthByiPhone6(10) * 2, messH);//信息内容lbl_content.frame = CGRectMake(f_CalcRealWidthByiPhone6(5), f_CalcRealHeightByiPhone6(25), Wi - f_CalcRealWidthByiPhone6(15) * 2, rect.size.height);
}
在这里,要切记如下几点:
1、设置文本行数
lbl_content.numberOfLines =0;
2、设置文本字体要和boundingRectWithSize中的字体保持一致
lbl_content.font =FONT_S_14;
3、如果还有控件在label下方,同时需要重新改变label下方控件的y坐标,其他不变
4、如果cell使用的xib文件拖拽的,还需要将这两个勾选去掉,因为这是自动调节,那我们改变的值不起作用,且重新布局时不要使用Masonry布局,使用它也不起作用,还是老老实实的使用frame吧
源码下载Demo下载
效果图如下: