【Swift】UILabel 设置内边距
前言
对应一个曾经开发 Android 的人来说,没有这些基础属性简直令人发指,还是表喷这个,认真写代码 - - #
声明
欢迎转载,但请保留文章原始出处:)
博客园:http://www.cnblogs.com
农民伯伯: http://over140.cnblogs.com
正文
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 } }
代码说明:
通过 IBInspectable 可以支持 UILable 在 Storyboard 里面就能指定内边距,非常方便:
参考
参考这篇文章 http://stackoverflow.com/questions/21167226/resizing-a-uilabel-to-accomodate-insets 改的,注意这篇文章 http://stackoverflow.com/questions/3476646/uilabel-text-margin 有问题。