美文网首页
UILabel内容自适应在UITableViewCell中显示

UILabel内容自适应在UITableViewCell中显示

作者: 毛菲斯 | 来源:发表于2017-08-04 16:56 被阅读0次

     首先我们在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中显示,自己总结的一点小小的经验,希望对你们有所帮助,如有其他好的方法,还希望您赐教!

    相关文章

      网友评论

          本文标题:UILabel内容自适应在UITableViewCell中显示

          本文链接:https://www.haomeiwen.com/subject/ycqblxtx.html