iOS给文本设置属性,并且计算文字行高

在开发中有时会遇到给文字属性设置行间距,段落高度等 这个怎么实现大家都应该知道,可是在设置完属性后再要计算文字行高,怎么做到了,项目中刚好遇到这个需求:现在记录下来

#define LINE_SPACE 4
#define  HEIGHT [ [ UIScreen mainScreen ] bounds ].size.height
//给文字设置行间距和字间距
* 1.先设置文字基本属性字典
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = LINE_SPACE; //设置行间距
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0; 
    paraStyle.paragraphSpacingBefore = 0.0; //段落缩进
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0; 
    NSDictionary *attriDic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
};//其中      NSKernAttributeName:@1.5f //设置字间距 

* 2 . 然后生成属性字符串:
NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];

当这样生成属性字符串后,需要计算等宽控件的文本高度可以这样计算:

    CGSize size = [str boundingRectWithSize:CGSizeMake(width, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attriDic context:nil].size;

当然计算文本的高度的方法有多种,这种算是比较简洁的一种了。

你可能感兴趣的:(iOS给文本设置属性,并且计算文字行高)