这就是我UILabel
的子类:
@IBDesignable class AttributedLabel: UILabel {
@IBInspectable var padding: CGFloat = 0
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(padding, padding, padding, padding)))
}
}
我在故事板中正确设置了padding
,但它不起作用,因为填充仍为0
。
如何让它发挥作用?是否可以在故事板中呈现它?
答案 0 :(得分:1)
您的子类看起来不完整。如文档中所述,您应该覆盖以下两种方法:
public func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect
public func drawTextInRect(rect: CGRect)
以下是一个应该有效的示例实现:
@IBDesignable class AttributedLabel : UILabel
{
@IBInspectable var padding: CGFloat = 0 {
didSet {
self.textInsets = UIEdgeInsets(top: self.padding, left: self.padding, bottom: self.padding, right: self.padding)
}
}
var textInsets = UIEdgeInsetsZero {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect
{
var insets = self.textInsets
let insetRect = UIEdgeInsetsInsetRect(bounds, insets)
let textRect = super.textRectForBounds(insetRect, limitedToNumberOfLines: numberOfLines)
insets = UIEdgeInsets(top: -insets.top, left: -insets.left, bottom: -insets.bottom, right: -insets.right)
return UIEdgeInsetsInsetRect(textRect, insets)
}
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, self.textInsets))
}
}
您将无法在Interface Builder中实时渲染它。
答案 1 :(得分:0)
像这样使用;更改顶部,底部,左侧,右侧插入填充。
@IBDesignable class AttributedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
由于