Adding space/padding to a UILabel

Annachiara picture Annachiara · Dec 13, 2014 · Viewed 248.1k times · Source

I have a UILabel where I want to add space in the top and in the bottom. With minimun height in constrainst I've modified it to:

enter image description here

EDIT: To do this I've used:

  override func drawTextInRect(rect: CGRect) {
        var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))

    } 

But I've to find a different method because if I write more than two lines the problem is the same:

enter image description here

Answer

Tai Le picture Tai Le · Sep 3, 2015

I have tried with it on Swift 4.2, hopefully it work for you!

@IBDesignable class PaddingLabel: UILabel {

    @IBInspectable var topInset: CGFloat = 5.0
    @IBInspectable var bottomInset: CGFloat = 5.0
    @IBInspectable var leftInset: CGFloat = 7.0
    @IBInspectable var rightInset: CGFloat = 7.0

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)
    }   

    override var bounds: CGRect {
        didSet {
            // ensures this works within stack views if multi-line
            preferredMaxLayoutWidth = bounds.width - (leftInset + rightInset)
        }
    } 
}

Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel

pod 'PaddingLabel', '1.2'

enter image description here