Search code examples
iosobjective-cautolayoutuilabel

Difficulty with UILabel width and Autolayout


I feel like this is a very simple question- I've searched high and low for an answer and came up with nothing. In my UITableViewController I set the text of a UILabel of my custom UITableViewCell (made in the storyboard). I want the width of the label to be the width of the text (which is not that difficult to calculate) PLUS a constant of about 20. I cant see to find a way of setting this? Should I have to just create the UILabel programmatically? Can autolayout not help me with this issue?


Solution

  • In interface builder this will probably be impossible as you've described it. One thing you can do is specify a different value for the label's intrinsic content size. Create a mini UILabel subclass:

    @interface Plus20UILabel : UILabel
    @end
    
    @implementation Plus20UILabel
    
    -(CGSize)intrinsicContentSize{
        CGSize contentSize = [super intrinsicContentSize];
        return CGSizeMake(contentSize.width + 20, contentSize.height);
    } 
    
    @end
    

    Then specify the label is a Plus20UILabel in IB. This will feed the new value into the AutoLayout engine and adjust the label and everything accordingly.