1.最通用最準(zhǔn)確的方法(包括表情空格)是用UITextView,布局時(shí)用UITextView代替label,關(guān)閉滑動(dòng)和交互就可以了揍很。
/**
@method 獲取指定寬度width的字符串在UITextView上的高度
@param textView 待計(jì)算的UITextView
@param Width 限制字符串顯示區(qū)域的寬度
@result float 返回的高度
*/
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return sizeToFit.height;
}
2.計(jì)算AttributedString的文字高度,經(jīng)過測(cè)試不是很準(zhǔn)...
- (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;
}