根据内容动态更改UILabel的高度 [英] Change the height of UILabel dynamically based on content

查看:85
本文介绍了根据内容动态更改UILabel的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UILabel作为UIButton的子视图,我正在传递值 从另一个视图并填充到UILabel中.现在,我想要那个UILabel 必须根据内容更改其高度.如果文本为"Hello",则必须 排成一行,但如果文字为我的文字太长而无法放入 标签",它必须更改其大小.我用过

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

但是为此,我需要在UILabel下留出空白空间.简直就是我 想要的是,当文本强度增加时,UILabel和UIView的大小 必须扩展.

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.

推荐答案

在下面使用您可以获取标签的高度

Using below you can get the height of the label

  • 文本-标签文本
  • 字体-标签中使用的字体
  • width-标签的宽度

  • 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;            
}

并使用高度创建框架

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

这篇关于根据内容动态更改UILabel的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆