无法在UILabel - iOS Swift中为文本添加边距/填充

时间:2017-07-20 14:52:30

标签: ios swift

基于this answer, 我在TextMarginLabel创建了一个UILabel子类,为UILabel中的文本添加了边距/填充。但它并没有增加任何余量,有人可以指导我出错的地方。

这是我的Subclassed标签

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

这里我创建标签,将其添加到视图并设置约束

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

向视图添加标签

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

观看Dict

let viewsDict = ["testingLabel" : testingLabel]

以下是为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))

0 个答案:

没有答案