某些时候,我们需要调整文字的显示范围(比如使用Label自定义提示语)已更美观的时候,最简单的方法就是继承UIlabel后重写UILable的相关方法;这里写swift的实现版本,OC的实现类似
首先我们需要一个新建的UIEdgeInsets属性,以及重新构造init方法
var edgesInset : UIEdgeInsets?
override init(frame: CGRect) {
super.init(frame: frame);
self.edgesInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
override func awakeFromNib() {
super.awakeFromNib()
self.edgesInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
接着重写他的rect范围
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect = super.textRect(forBounds: UIEdgeInsetsInsetRect(bounds, self.edgesInset!), limitedToNumberOfLines: numberOfLines)
rect.origin.x = rect.origin.x - (self.edgesInset?.left)!
rect.origin.y = rect.origin.y - (self.edgesInset?.top)!
rect.size.width = rect.size.width + (self.edgesInset?.left)! + (self.edgesInset?.right)!
rect.size.height = rect.size.height + (self.edgesInset?.top)! + (self.edgesInset?.bottom)!
return rect
}
最后自然是重绘文字的显示范围
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, self.edgesInset!))
}
ok,这就搞定了,之所以重新定制Label的文字范围,是因为要写一个通用的提示,依托于snp就可以很轻易的实现,而不需要去引入第三方库