Adjust UILabel height depending on the text

前端 未结 30 1776
走了就别回头了
走了就别回头了 2020-11-22 03:53

Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players m

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:23

    You may use it as a method, as well. @Pyjamasam is very much true so i am just making its method. It may be helpfull for some one else

    -(CGRect)setDynamicHeightForLabel:(UILabel*)_lbl andMaxWidth:(float)_width{
        CGSize maximumLabelSize = CGSizeMake(_width, FLT_MAX);
    
        CGSize expectedLabelSize = [_lbl.text sizeWithFont:_lbl.font constrainedToSize:maximumLabelSize lineBreakMode:_lbl.lineBreakMode];
    
        //adjust the label the the new height.
        CGRect newFrame = _lbl.frame;
        newFrame.size.height = expectedLabelSize.height;
        return newFrame;
    }
    

    and just set it like this

    label.frame = [self setDynamicHeightForLabel:label andMaxWidth:300.0];
    

提交回复
热议问题