小凡慢慢学
慢慢学,更有趣

在iOS 7之前,常用下面这个方法计算文本高度

sizeWithFont:constrainedToSize:lineBreakMode:(Deprecated in iOS 7.0

但是到了iOS 7 之后,这个方法就不建议使用了。提示用下面这个方法:

boundingRectWithSize:options:attributes:context:(Available in iOS 7.0 and later.)

 

 1 -(CGSize)GetHeightDyanamic:(UILabel*)lbl
 2 {
 3     NSRange range = NSMakeRange(0, [lbl.text length]);
 4     CGSize constraint;
 5         constraint= CGSizeMake(287 ,MAXFLOAT);
 6     CGSize size;
 7     NSString *ver = [[UIDevice currentDevice] systemVersion];
 8     float ver_float = [ver floatValue];
 9     if (ver_float>6.0) {//版本
10         NSDictionary *attributes = [lbl.attributedText attributesAtIndex:0 effectiveRange:&range];
11         CGSize boundingBox = [lbl.text boundingRectWithSize:constraint options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
12         
13         size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
14     }
15     else{
16         
17         
18         size = [lbl.text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
19     }
20     return size;
21 }

//使用方法
UILabel *_lblSelectedCountryNames;
1         _lblSelectedCountryNames.text=[ArryData componentsJoinedByString:@"\n"];
2         CGSize size=[self GetHeightDyanamic:_lblSelectedCountryNames];
3         _lblSelectedCountryNames.frame=CGRectMake(16, 240, 287, size.height);
posted on 2014-04-17 15:07  小凡慢慢学  阅读(271)  评论(0编辑  收藏  举报