关闭

iOS - UILabel根据文字计算高度,设置字间距,行间距

标签: iOSLabel高度字间距行间距
2592人阅读 评论(0) 收藏 举报
分类:

根据文字长度计算高度

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
label.text = string;
label.backgroundColor = BGCOLOR;
label.textAlignment = NSTextAlignmentLeft;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
label.font  = [UIFont systemFontOfSize:15];

CGRect txtFrame = label.frame;

txtFrame.size.height =[label.text boundingRectWithSize:CGSizeMake(txtFrame.size.width, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                            attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil]
                                               context:nil].size.height;

label.frame = CGRectMake(10, 150, 300, txtFrame.size.height);
[self.view addSubview:label];

设置label字间距,行间距

UILabel *spacingLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 280, 50)];
spacingLabel.text = self.allDataArray[indexPath.row][@"content"];
spacingLabel.numberOfLines = 0;
spacingLabel.font  = [UIFont systemFontOfSize:12];
spacingLabel.textColor = [UIColor darkGrayColor];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:8];

NSMutableAttributedString *attributedString =  [[NSMutableAttributedString alloc] initWithString:spacingLabel.text attributes:@{NSKernAttributeName : @(1.5f)}];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, spacingLabel.text.length)];

spacingLabel.attributedText = attributedString;


CGSize size = CGSizeMake(280, 500000);
CGSize labelSize = [spacingLabel sizeThatFits:size];
spacingLabel.frame = CGRectMake(20, 50, labelSize.width, labelSize.height);

[cell.contentView addSubview:spacingLabel];


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:86978次
    • 积分:1399
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:4篇
    • 译文:0篇
    • 评论:103条
    文章分类
    最新评论