在使用Xib开发的时候,除了设置Label的外边距约束的时候,还会想设置下内边距即前端的padding,但Xib设置Label的padding并不直观,下面添加几个属性让Xib设置更简单。
让XIb开发时更直观的设置Label的padding。
@IBDesignable
class RadiusLabel: UILabel{
private var padding = UIEdgeInsets.zero
@IBInspectable
var paddingLeft: CGFloat {
get { return padding.left }
set { padding.left = newValue }
}
@IBInspectable
var paddingRight: CGFloat {
get { return padding.right }
set { padding.right = newValue }
}
@IBInspectable
var paddingTop: CGFloat {
get { return padding.top }
set { padding.top = newValue }
}
@IBInspectable
var paddingBottom: CGFloat {
get { return padding.bottom }
set { padding.bottom = newValue }
}
//重新绘制文本
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
//重新text文字框大小
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insets = self.padding
var rect = super.textRect(forBounds:bounds.inset(by: insets), limitedToNumberOfLines: numberOfLines)
rect.origin.x -= insets.left
rect.origin.y -= insets.top
rect.size.width += (insets.left + insets.right)
rect.size.height += (insets.top + insets.bottom)
return rect
}
}
在Xib属性看到上下左右padding属性修改即可。