我想在标签内添加填充,以便在标签与其边框之间留出间隔。我为此创建了一个从UILabel扩展的类。
UILabelPadding.swift:
import UIKit
class UILabelPadding: UILabel {
let padding = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, 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)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let superSizeThatFits = super.sizeThatFits(size)
let width = superSizeThatFits.width + padding.left + padding.right
let heigth = superSizeThatFits.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}
}
然后将myLabel的类型从UILabel更改为UILabelPadding。在我的UIViewController中,设置myLabel的文本,调用sizeToFit(),然后将边框和背景色添加到myLabel中:
myLabel.text = "label test"
myLabel.sizeToFit()
//background + border
myLabel.layer.borderColor = UIColor(red: 27/255, green: 100/255, blue: 90/255, alpha: 1.0).cgColor
myLabel.layer.backgroundColor = UIColor(red: 27/255, green: 100/255, blue: 90/255, alpha: 1.0).cgColor
myLabel.layer.cornerRadius = 9
myLabel.layer.masksToBounds = true
myLabel.layer.borderWidth = 1
添加了边框和背景色,但填充无效。当我调试时,从不调用sizeThatFits()。
有什么帮助吗?
最佳答案
我解决了这个问题!
对于那些如何面对相同的问题:
1-创建一个从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-将标签的类型设置为UILabelPadding,并确保在 Storyboard 中也设置了该类型。