根据内容动态更改UILabel的高度

根据内容动态更改UILabel的高度

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

问题描述

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

I have a UILabel as subview of UIButton and I am passing the valuefrom another view and populating in UILabel. Now, I want that UILabelmust change its height based on the content.If text is "Hello" it mustbe in 1 line but if text is " my text is too long to fit in thelabel", 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 Iwant is that when text strength increases,size of UILabel and UIViewmust 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的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 11:31