Change the height of UILabel dynamically based on content

前端 未结 4 987
自闭症患者
自闭症患者 2020-12-06 08:49

I have a UILabel as subview of UIButton and I am passing the value from another view and populating in UILabel. Now, I want that

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 09:08

    Using below you can get the height of the label

    • text - text of the label
    • font - font used in label
    • width - width of the label

      -(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
          CGSize constraint = CGSizeMake(width , 20000.0f);
          CGSize title_size;
          float totalHeight;
      
          SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
          if ([text respondsToSelector:selector]) {                
              title_size = [text boundingRectWithSize:constraint
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{ NSFontAttributeName : font }
                                              context:nil].size;
      
              totalHeight = ceil(title_size.height); 
          } else {                
              title_size = [text sizeWithFont:font
                            constrainedToSize:constraint
                                lineBreakMode:NSLineBreakByWordWrapping];                
              totalHeight = title_size.height ;                
          }
      
          CGFloat height = MAX(totalHeight, 40.0f);
          return height;            
      }
      

    and create a frame using the height

    CGRect frame = questionTitleLbl.frame;
    
    float height = [self getHeightForText:questionTitleLbl.text 
                                 withFont:questionTitleLbl.font
                                andWidth:questionTitleLbl.frame.size.width];
    float gap = 2;
    
    cell.questionTitleLbl.frame = CGRectMake(frame.origin.x, 
                                             frame.origin.y, 
                                             frame.size.width, 
                                             height);
    

提交回复
热议问题