UILabel内容自适应在UITableViewCell中显示

 首先我们在cell.h中定义 一个方法

+ (CGFloat)getCellHeightContent:(NSString *)content;

在cell.m 中实现这个方法

首先第一步 自己先要实现以下方法

+ (CGFloat)getHeightText:(NSString *)text font:(UIFont *)font labelWidth:(CGFloat)width{

NSDictionary *attrDic = @{NSFontAttributeName:font};

CGRect strRect = [text boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attrDic context:nil];

return strRect.size.height;

}

在来实现我们前面定义的那个方法

+(CGFloat)getCellHeightContent:(NSString *)content{

CGFloat margin = 60 * FitHeight;//这个是你除去label的高度,显示在cell中其他控件的高度

return [self  getHeightText:content font:tabFont labelWidth:ScreenWidth - 100 * FitWidth] + margin;

}


接着我们在ViewController.h页面中调用就可以了

在这个方法里我们首先要定义label的位置,赋值,高度(label的内容是自适应的)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

cell.ContentLabel.text = [NSString stringWithFormat:@"%@",CommentModel.content];

cell.ContentLabel.numberOfLines = 0;

cell.ContentLabel.lineBreakMode = NSLineBreakByWordWrapping;

CGSize size = [cell.ContentLabel sizeThatFits:CGSizeMake(ScreenWidth - 100 * FitWidth, MAXFLOAT)];//根据文字的长度返回一个最佳宽度和高度

cell.ContentLabel.frame = CGRectMake(cell.HeadPortraitimage.x + cell.HeadPortraitimage.width + 10 * FitWidth, cell.NameLabel.y + cell.NameLabel.height, ScreenWidth - 100 * FitWidth, size.height);//label的位置宽度和高度自适应

}

最后我们来定义cell的高度  这个时候我们就要调用我们前面写的那个方法

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

CommentListModel * CommentModel = self.CommentArray[indexPath.row];//用你自己的cell

return [CommentTableViewCell getCellHeightContent:[NSString stringWithFormat:@"%@",CommentModel.content]];//这里注意,要给你的label赋一次值

}

注:这是我在做一个项目中给新闻评论的内容来自适应,并把这个内容一起放到UITableViewCell中显示,自己总结的一点小小的经验,希望对你们有所帮助,如有其他好的方法,还希望您赐教!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容