前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >UILabel显示固定行数的问题

UILabel显示固定行数的问题

作者头像
用户1451823
发布2018-09-13 15:47:31
1.3K0
发布2018-09-13 15:47:31
举报
文章被收录于专栏:DannyHoo的专栏DannyHoo的专栏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337811

在项目中我们有时会遇到这样的需求:显示一段文字,但这段文字最多显示4行。

我们首先考虑没有行数显示的情况:

UILabel * lbl = [UILabel alloc init];

    lbl.backgroundColor = UIColor redColor;

    lbl.textColor = UIColor blackColor;

    lbl.numberOfLines = 0;

    lbl.text = @"连卡精神分裂就离开家啊";

    lbl.lineBreakMode = UILineBreakModeWordWrap;

NSMutableDictionary * dic = NSMutableDictionary dictionary;

    dicNSFontAttributeName = UIFont systemFontOfSize:17;

CGRect rect = lbl.text boundingRectWithSize:CGSizeMake(100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil;

NSLog(@"%f-----%f", rect.size.width, rect.size.height);

    lbl.frame = (CGRect){{0, 20}, rect.size};

    self.view addSubview:lbl;

这样单元格高度会进行自适应。

如果显示固定行数,我们需要知道固定行数时单元格的高度

UILabel * lbl = [UILabel alloc init];

    lbl.backgroundColor = UIColor redColor;

    lbl.textColor = UIColor blackColor;

    lbl.numberOfLines = 0;

    lbl.text = @"连卡精神分裂就离开家啊";

    lbl.lineBreakMode = UILineBreakModeWordWrap;

NSMutableDictionary * dic = NSMutableDictionary dictionary;

    dicNSFontAttributeName = UIFont systemFontOfSize:17;

CGRect rect = lbl.text boundingRectWithSize:CGSizeMake(100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil;

NSLog(@"%f-----%f", rect.size.width, rect.size.height);

    lbl.frame = (CGRect){{0, 20}, rect.size};

if (rect.size.height > 102) {

        lbl.numberOfLines = 5;

        lbl.frame = (CGRect){{0, 20}, {100, 101.435547}};

    }

    self.view addSubview:lbl;

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016年11月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档