Search code examples
iosswiftautolayoutnslayoutconstraint

How to resize UILabel width to fit text using autolayout?


I have a UILabel with the following constraints

Height = 30
Leading = superview leading
Center Y = superview center Y

Text of the label changes based on api response. I was using label.sizeToFit() to change the width of the label.

Now I want to add some space to the label. New width should be

textsize + 50

How can I do this without calculating the width, only using autolayout.


Solution

  • We generally do not add padding to a label. We use another solution:

    1. You can increase leading and trailing constraints from 0 to whatever you need.
    2. You can create another UIView on which you place your label. The label should have leading and trailing constraints as much as you want your padding. This should automatically resize your view
    3. Use UIButton which already has content insets in Storyboard. Disable its user interaction. (It is an overkill but it is A solution).

    If you really really want this though you can create a subclass of UILabel and add this functionality in just few lines:

    @IBDesignable class AppLabel: UILabel {
    
        @IBInspectable var horizontalPadding: CGFloat = 0.0 { didSet { invalidateIntrinsicContentSize() } }
        @IBInspectable var verticalPadding: CGFloat = 0.0 { didSet { invalidateIntrinsicContentSize() } }
    
        override var intrinsicContentSize: CGSize {
            var size = super.intrinsicContentSize
            size.width += horizontalPadding*2.0
            size.height += verticalPadding*2.0
            return size
        }
    
    }
    

    Now you can even in storyboard set vertical and horizontal padding. But you need to have center text alignment. The key is overriding intrinsicContentSize which is what defines this automatic sizing. Simply some value is added to it and it works.

    I would personally still avoid this but perhaps it is still better than using UIButton.