Search code examples
objective-cuiviewios6uilabel

How to change UIView's height based on UILablel's height inside it?


I have a UIView containing only one UILabel. This UILabel is used to display some information which may be of different length. I calculate height of UILabel using [label.text sizeWithFont:label.font constrainedToSize:label.bounds.size lineBreakMode:label.lineBreakMode] method. But how to resize UIView's height based on UILabel's height?


Solution

  • [label.superview setFrame:label.frame];
    

    That in principle should do. You may want to add a bit more logic and build some margins/paddings in. Meaning you will have to split self.frame up into coordinates, add some offsets and create a new frame from it with CGFrameMake and assign that to the superviews frame.

    [label.superview setFrame: CGFrameMake(0, 0, label.frame.size.width + 2*label.frame.origin.x, label.frame.size.height + 2*label.frame.origin.y)];
    

    Take the second just as a sugestion. It will set the origin to 0 because the lable's frame may not be 0. Then it adds room for some margin around the lable assuming that the left margin and the right one are the same and the top margin and the bottom margin are the same too.