UILabel border and padding

I use a label subclass that does much what you describe. It looks like this:

class MyBoundedLabel: UILabel {
    override func drawText(in rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        context.stroke(self.bounds.insetBy(dx: 1.0, dy: 1.0))
        super.drawText(in: rect.insetBy(dx: 5.0, dy: 5.0))
    }
}

You might try that, and then jiggle the numbers and other details so they look like what you want.


I solved the issue!

For those how are facing the same problem:

1- Make a class extending from UILabel:

UILabelPadding.swift:

class UILabelPadding: UILabel {

    let padding = UIEdgeInsets(top: 2, left: 8, bottom: 2, right: 8)
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: padding))
    }

    override var 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)
    }



}

2- Set the type of your label to the UILabelPadding and make sure that the type is set also in the storyboard.

Tags:

Ios

Swift