0

I want to add left padding to text in a UILabel programmatically. I've searched for a solution but nothing that I can get to work within my existing UILabel extension.

class TopSideHeaderLabel: UILabel {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        adjustsFontSizeToFitWidth = true
        font = UIFont(name: Theme.PrimaryFontSemiBold, size: 16)
        textColor = Theme.White

        backgroundColor = Theme.background2
        textAlignment = .left
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
k.thomas
  • 51
  • 7
  • 1
    [UILabel text margin](https://stackoverflow.com/questions/3476646/uilabel-text-margin)? [Adding space/padding to a UILabel](https://stackoverflow.com/questions/27459746/adding-space-padding-to-a-uilabel/39998301)? [Adding Insets to a UILabel](https://blog.chrishannah.me/adding-insets-to-a-uilabel/)? [Swift Tool Belt, Part 3: Extending UILabel](https://spin.atomicobject.com/2017/08/04/swift-extending-uilabel/)? [Add padding to UILabel in Swift](http://fabcoding.com/add-padding-to-uilabel-in-swift/)? – MadProgrammer Jul 07 '19 at 21:46

1 Answers1

1

What about using insets?

class TopSideHeaderLabel: UILabel {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        adjustsFontSizeToFitWidth = true
        font = UIFont(name: Theme.PrimaryFontSemiBold, size: 16)
        textColor = Theme.White

        backgroundColor = Theme.background2
        textAlignment = .left
    }

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }
}
barbarity
  • 2,420
  • 1
  • 21
  • 29