2

I have created a label from storyboard and now I am trying to give padding to that label. I have create a class and tried both the methods below but nothing is working. Please help.

override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)))

    }


 let padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)


override func intrinsicContentSize() -> CGSize {
    let superContentSize = super.intrinsicContentSize()
    let width = superContentSize.width + padding.left + padding.right
    let heigth = superContentSize.height + padding.top + padding.bottom
    return CGSize(width: width, height: heigth)
}
Chatar Veer Suthar
  • 15,541
  • 26
  • 90
  • 154
laxman khanal
  • 998
  • 1
  • 8
  • 18

1 Answers1

5

Try this, I have used and it worked from SO itself

@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 drawTextInRect(rect: CGRect) {
        let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
    }

    override func intrinsicContentSize() -> CGSize {
        var intrinsicSuperViewContentSize = super.intrinsicContentSize()
        intrinsicSuperViewContentSize.height += topInset + bottomInset
        intrinsicSuperViewContentSize.width += leftInset + rightInset
        return intrinsicSuperViewContentSize
    }
}

Reference: Adding space/padding to a UILabel

Community
  • 1
  • 1
Deepraj Chowrasia
  • 1,349
  • 10
  • 20