-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathUILabel.swift
80 lines (65 loc) · 2.1 KB
/
UILabel.swift
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// UILabel.swift
// UIKit
//
// Created by Chris on 19.06.17.
// Copyright © 2017 flowkey. All rights reserved.
//
public enum NSTextAlignment: Int {
case center
case left
case right
internal func contentsGravity() -> CALayerContentsGravity {
switch self {
case .left: return .left
case .center: return .center
case .right: return .right
}
}
}
@MainActor
open class UILabel: UIView {
open var numberOfLines: Int = 1 {
didSet { if numberOfLines != oldValue { setNeedsDisplay() } }
}
open var text: String? {
didSet { if text != oldValue { setNeedsDisplay() } }
}
open var textColor: UIColor = .black {
didSet { if textColor != oldValue { setNeedsDisplay() } }
}
open var textAlignment: NSTextAlignment = .left {
didSet { updateLayerContentsGravityFromTextAlignment() }
}
private func updateLayerContentsGravityFromTextAlignment() {
layer.contentsGravity = textAlignment.contentsGravity()
}
open var font: UIFont = .systemFont(ofSize: 16) {
didSet { if font != oldValue { setNeedsDisplay() } }
}
override open var frame: CGRect {
didSet { if oldValue.size != frame.size { setNeedsDisplay() } }
}
open override func draw() {
super.draw()
let wrapLength = (numberOfLines != 1) ? bounds.width : 0
layer.contents = font.render(text, color: textColor, wrapLength: wrapLength)
}
override open func display(_ layer: CALayer) {
self.draw()
}
override public init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = false
updateLayerContentsGravityFromTextAlignment()
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
guard let text = self.text else { return .zero }
let wrapLength = (numberOfLines != 1) ? bounds.width : 0
return text.size(with: self.font, wrapLength: wrapLength)
}
open var shadowColor: UIColor? {
get { return layer.shadowColor }
set { layer.shadowColor = newValue?.cgColor }
}
}