1.单行文本高度计算
define VPTEXTSIZE(text, font) [text length] > 0 ? [text \
sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero
2.默认不设置行间距时,单行多行都可以
-
(CGSize)heightWithFont:(UIFont *)font
MaxWidth:(float)width{
if (self.length==0) {
return CGSizeMake(0, 0);
}
CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin|
NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:font}
context:nil];return CGSizeMake((rect.size.width), (rect.size.height));
}
2.设置行间距的情况
多行的情况
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 12;
NSDictionary *dic = @{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:[UIFont systemFontOfSize:14]};
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:text attributes:dic];
text4.attributedText = attrString;
-
(CGFloat)heightWithStringAttribute:(NSDictionary <NSString *, id> *)attribute fixedWidth:(CGFloat)width {
NSParameterAssert(attribute);
CGFloat height = 0;
if (self.length) {
CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil]; height = rect.size.height;
}
return height;
}
当文本为单行时候又设置了行间距(纯英文的情况没有问题),但是包含有中文的时候计算的高度就会有问题
height=[text heightWithStringAttribute:dic1 fixedWidth:[UIScreen mainScreen].bounds.size.width-20*2];
if ((height - [UIFont systemFontOfSize:14].lineHeight) <= paragraphStyle.lineSpacing) {//是否是单行
if ([self containChinese:text]) { //如果包含中文
height = height-paragraphStyle.lineSpacing;
// height = [NSString aLineOfTextHeightWithStringAttribute:dic1];
}
tex5.text=text; //单行的情况就不能设置为attributedText了
}else{
tex5.attributedText = attrString;
}
-
(CGFloat)aLineOfTextHeightWithStringAttribute:(NSDictionary <NSString *, id> *)attribute {
CGFloat height = 0;
CGRect rect = [@"One" boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil];height = rect.size.height;
return height;
}