某些時候,我們需要調(diào)整文字的顯示范圍(比如使用Label自定義提示語)已更美觀的時候,最簡單的方法就是繼承UIlabel后重寫UILable的相關(guān)方法;這里寫swift的實現(xiàn)版本,OC的實現(xiàn)類似
首先我們需要一個新建的UIEdgeInsets屬性,以及重新構(gòu)造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就可以很輕易的實現(xiàn),而不需要去引入第三方庫