前言ide
對應一個曾經開發 Android 的人來講,沒有這些基礎屬性簡直使人髮指,仍是表噴這個,認真寫代碼 - - #ui
聲明
歡迎轉載,但請保留文章原始出處:)
博客園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.comspa
正文code
class UILabelPadding : UILabel { private var padding = UIEdgeInsetsZero @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 drawTextInRect(rect: CGRect) { super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding)) } override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { let insets = self.padding var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, 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 } }
代碼說明:blog
經過 IBInspectable 能夠支持 UILable 在 Storyboard 裏面就能指定內邊距,很是方便:開發
參考get
參考這篇文章 http://stackoverflow.com/questions/21167226/resizing-a-uilabel-to-accomodate-insets 改的,注意這篇文章 http://stackoverflow.com/questions/3476646/uilabel-text-margin 有問題。博客
結束it
抱歉命名用的 Android 的,而後超愛 IBInspectable 這個東西。io