iOS UIKit框架默认只能通过UILable的textAlignment属性调整其水平方向上的布局,设置文字水平居左、居中和居右。不能对文字垂直方向上的布局做出直接调整,但是我们通过重写UILabel的textRectForBounds和drawTextInRect方法,能够很便捷的调整UILable的内容布局,实现居上、垂直居中和居下的效果。具体实现如下:

创建VerticalAlignment枚举

1
2
3
4
5
enum VerticalAlignment {
case Top
case Middle
case Bottom
}

重写UILabel

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
class HLable: UILabel {

override init(frame: CGRect) {
self.verticalAlignment = .Middle
super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
self.verticalAlignment = .Middle
super.init(coder: aDecoder)
}

var verticalAlignment: VerticalAlignment {
didSet {
self.setNeedsDisplay()
}
}

override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var textRect = super.textRectForBounds(bounds, limitedToNumberOfLines: numberOfLines)
switch self.verticalAlignment {
case .Top:
textRect.origin.y = bounds.origin.y
case .Bottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height
case .Middle:
textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0
}
return textRect
}

override func drawTextInRect(rect: CGRect) {
let actualRect = self.textRectForBounds(rect, limitedToNumberOfLines: numberOfLines)
super.drawTextInRect(actualRect)
}
}

使用方法

1
2
let label = HLabel()
label.verticalAlignment = .Top