1.最通用最准确的方法(包括表情空格)是用UITextView,布局时用UITextView代替label,关闭滑动和交互就可以了。
/**
@method 获取指定宽度width的字符串在UITextView上的高度
@param textView 待计算的UITextView
@param Width 限制字符串显示区域的宽度
@result float 返回的高度
*/
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return sizeToFit.height;
}
2.计算AttributedString的文字高度,经过测试不是很准...
- (float) heightForString:(NSString*)value fontSize:(float)fontSize andWidth:(float)width{
UITextView*detailTextView = [[UITextViewalloc]init];
detailTextView.textContainerInset=UIEdgeInsetsZero;
detailTextView.font=font(fontSize);
NSMutableParagraphStyle*paragraphStyle = [[NSMutableParagraphStylealloc]init];
paragraphStyle.lineSpacing=5;//字体的行间距
NSDictionary*attributes =@{
NSFontAttributeName:[UIFontsystemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle
};
NSMutableAttributedString*attributeText = [[NSMutableAttributedStringalloc]initWithString:value attributes:attributes];
detailTextView.attributedText=attributeText;
CGSizedeSize = [detailTextViewsizeThatFits:CGSizeMake(width,MAXFLOAT)];
returndeSize.height;
}
网友评论