1.單行文本高度計算
define VPTEXTSIZE(text, font) [text length] > 0 ? [text \
sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero
2.默認不設(shè)置行間距時,單行多行都可以
-
(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.設(shè)置行間距的情況
多行的情況
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;
}
當(dāng)文本為單行時候又設(shè)置了行間距(純英文的情況沒有問題)牍帚,但是包含有中文的時候計算的高度就會有問題
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; //單行的情況就不能設(shè)置為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;
}