2

Based on this answer, I have created a TextMarginLabel subclassed from UILabel to add margin/padding to text inside the UILabel. But it doesn't add any margin, could someone please guide where I'am going wrong.

Here is my Subclassed label

class TextMarginLabel: UILabel {
    //override func drawText(in rect: CGRect) {
    override public func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets.init(top: 10, left: 5, bottom: 10, right: 5)
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }
}

Here I am creating the label, adding it to the view and setting constraints

override func viewDidLoad() {
    super.viewDidLoad()
    let testingLabel : TextMarginLabel = {
        let label       = TextMarginLabel()
        label.text      = "This is a test label"
        label.backgroundColor = UIColor.white
        return label
    }()
 ....
}

Adding label to the view

self.view.addSubview(testingLabel)
testingLabel.translatesAutoresizingMaskIntoConstraints = false

Views Dict

let viewsDict = ["testingLabel" : testingLabel]

Here are the constraints set for the testingLabel

self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[testingLabel]", options: [], metrics: nil, views: viewsDict))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[testingLabel]|", options: [], metrics: nil, views: viewsDict))
kurrodu
  • 2,108
  • 4
  • 32
  • 49
  • There's differences. They may not matter, but you are (1) setting a bottom set and (2) adding constraints. In order to remove these things from your issue - and to be of help - could you be more specific as to what you mean by "it doesn't add any margin"? Thanks. –  Jul 20 '17 at 15:12
  • I was expecting the text in my subclassed label to have margins as per the UIEdgeInsets. But it still doesn't have margins. – kurrodu Jul 20 '17 at 16:59

0 Answers0