原文: http://www.cnblogs.com/A--G/p/4819189.html
iOS 2.0之后 sizeWithFont就被弃用了:
1 //计算textview 高度 2 - (float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText{ 3 4 // float fPadding = 16.0; // 8.0px x 2 5 // CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX); 6 // 7 // CGSize size = [strText sizeWithFont: textView.font constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 8 9 // float fHeight = size.height + 16.0;
可以采用boundingRectWithSize,这里举个栗子~
1 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init]; 2 paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; 3 NSDictionary *attributes = @{NSFontAttributeName:textView.font, NSParagraphStyleAttributeName:paragraphStyle.copy}; 4 5 float fPadding = 16.0; // 8.0px x 2 6 CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX); 7 8 CGSize size = [strText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size; 9 10 float fHeight = size.height + 16.0; 11 12 return fHeight;