Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

objective c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...