获取文字高度以及根据label内容来调整label的高度

ios7以上已经摒弃 sizeWithFont 这个方法,需要用到 boundingRectWithSize 来获取文字的高度
1
2
3
4
5
6
7
8
9
10
11
12
UIFont *font = [UIFont fontWithName:@"Arial" size:14];//跟label的字体大小一样
   CGSize size = CGSizeMake(300, 29999);//跟label的宽设置一样
   if (is_IOS_7)
   {
       NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
        
       size =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
   }
   else
   {
       size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];//ios7以上已经摒弃的这个方法
   }

 

UILabel根据内容自动调整高度 

sizeWithFont已经被Apple抛弃了,但还是可以用的
1
2
CGSize size = [news_str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, size.width, size.height);

 

iOS7出来以后,以前的UILabel根据内容获得高度和宽度不建议用了,虽然还可以用,但是总有有强迫症的,不希望有警告,这段代码是iOS7以后UILabel可以根据内容改变高度和宽度。
1
2
3
4
5
6
7
8
NSString *str = @"866.44";
UIFont *font = [UIFont systemFontOfSize:13];
CGSize size = CGSizeMake(320,2000);
CGRect labelRect = [str boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, labelRect.size.width, labelRect.size.height)];
label.text = str;
label.font = [UIFont systemFontOfSize:13];
[self.view addSubview: label];

 

  1. /*根据label内容来调整label的高度*/ 
  2. - (void)resizeLabelByContent:(UILabel *)label 
  3.     CGSize maxSize = CGSizeMake(label.width, 999); 
  4.     label.numberOfLines = 0; 
  5.     NSString *contentStr = label.text; 
  6.     UIFont *contentFont = label.font; 
  7.   
  8.     CGRect contentFrame; 
  9.   
  10.     NSString *version = [[UIDevice currentDevice] systemVersion]; 
  11.     if ([version floatValue] < 7.0) { 
  12.         CGSize contentStringSize = [contentStr sizeWithFont:contentFont                 constrainedToSize:maxSize lineBreakMode:label.lineBreakMode]; 
  13.         contentFrame = CGRectMake(label.left, label.top, label.width,               contentStringSize.height); 
  14.     } else { 
  15.         NSDictionary *contentDic = [NSDictionary                dictionaryWithObjectsAndKeys:contentFont, NSFontAttributeName, nil]; 
  16.         CGSize contentStrSize = [contentStr boundingRectWithSize:maxSize                options:NSStringDrawingUsesLineFragmentOrigin attributes:contentDic                 context:nil].size; 
  17.         contentFrame = CGRectMake(label.left, label.top, label.width,           contentStrSize.height); 
  18.     } 
  19.     label.frame = contentFrame; 

 

posted on 2014-07-30 13:35  恒山之阳  阅读(245)  评论(0编辑  收藏  举报

导航