Change the height of UILabel dynamically based on content

Sushil Sharma picture Sushil Sharma · Aug 6, 2014 · Viewed 13.9k times · Source

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 UILabel must change its height based on the content.If text is "Hello" it must be in 1 line but if text is " my text is too long to fit in the label", it must change its size. I have used

   [self.addressLabel sizeToFit];

But for this i need to leave empty space below UILabel. Simply what I want is that when text strength increases,size of UILabel and UIView must expand.

Answer

karthik picture karthik · Aug 6, 2014

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);