我有以下4种方法在UITextView中获取文本高度。我发现价值可能会有所不同。根据我的测试,有时method1和method4是正确的,有时method3是正确的。我无法弄清楚这些是怎么发生的。
//method 1
float fudgeFactor = [self getTextViewLeftMargin:textView];
CGSize tallerSize = CGSizeMake(textView.frame.size.width-fudgeFactor*2,999);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:NSLineBreakByWordWrapping];
} else {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
}
CGFloat textHeight = stringSize.height;
//method2:
CGFloat textHeight2 = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, FLT_MAX)].height;
//method3:
CGFloat textHeight3 = textView.contentSize.height;
//method4:
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr = @{NSFontAttributeName: textView.font};
CGRect labelBounds = [textView.text boundingRectWithSize:tallerSize
options:options
attributes:attr
context:nil];
CGFloat textHeight = labelBounds.size.height;