前言
对应一个曾经开发 Android 的人来说,没有这些基础属性简直令人发指,还是表喷这个,认真写代码 - - #
正文
代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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 里面就能指定内边距,非常方便:
以上就是Swift UILable 设置内边距实例代码,开发IOS应用需要用的可以参考下。