/**
控制显示一行半的方法
@param originalContent 原内容
@param labelWidth label宽度
@return 展示的内容
*/
- (NSMutableAttributedString *)getSubContentWithOriginalContent:(NSMutableAttributedString *)originalContent andLabelWidth:(CGFloat)labelWidth{
NSAttributedString *subContent = nil;
CGFloat maxLength = labelWidth * 1.5;//设置字符串最大长度为一行半
CGFloat length = 0;
for(int i = 0; i < [originalContent length]; i++)
{
subContent = [originalContent attributedSubstringFromRange:NSMakeRange(i,1)];
// 计算宽度
CGSize size = [subContent boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine context:nil].size;
length = length + size.width;
//此处截取maxLength,根据需求设置
if (length >= maxLength) {
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithAttributedString:[originalContent attributedSubstringFromRange:NSMakeRange(0, i)]];
NSAttributedString *att = [[NSAttributedString alloc] initWithString:@" ..." attributes:self.attributeStyle];
[resultString appendAttributedString:att];
return resultString;
}
}
return originalContent;
}
网友评论