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 有问题。
本文转自博客园农民伯伯的博客,原文链接:【Swift】UILabel 设置内边距,如需转载请自行联系原博主。
时间: 2024-10-02 21:49:20