基于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))