objective-cuilabelios7.1xcode5.1

Change the height of UILabel dynamically based on content


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.


Solution

  • Using below you can get the height of the label

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