方法一:
- (CGSize)getStrRectInText:(NSString *)string InTextView:(UITextView *)textView;
{
//实际textView显示时我们设定的宽
CGFloat contentWidth = CGRectGetWidth(textView.frame);
//但事实上内容需要除去显示的边框值
CGFloat broadWith = (textView.contentInset.left + textView.contentInset.right
+ textView.textContainerInset.left
+ textView.textContainerInset.right
+ textView.textContainer.lineFragmentPadding/*左边距*/
+ textView.textContainer.lineFragmentPadding/*右边距*/);
NSLog(@"broadWith:%f",broadWith);
CGFloat broadHeight = (textView.contentInset.top
+ textView.contentInset.bottom
+ textView.textContainerInset.top
+textView.textContainerInset.bottom);//+self.textview.textContainer.lineFragmentPadding/*top*//*+theTextView.textContainer.lineFragmentPadding*//*there is no bottom padding*/);
//由于求的是普通字符串产生的Rect来适应textView的宽
contentWidth -= broadWith;
CGSize InSize = CGSizeMake(contentWidth, MAXFLOAT);
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = textView.textContainer.lineBreakMode;
NSDictionary *dic = @{NSFontAttributeName:textView.font, NSParagraphStyleAttributeName:[paragraphStyle copy]};
CGSize calculatedSize = [string boundingRectWithSize:InSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
CGSize adjustedSize = CGSizeMake(ceilf(calculatedSize.width),calculatedSize.height + broadHeight);//ceilf(calculatedSize.height)
return adjustedSize;
}
方法二:
- (CGFloat)getHeightForString:(UITextView *)textView andWidth:(CGFloat)width{
CGSize sizeFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return sizeFit.height;
}