This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
NELineLabel.swift
79 lines (61 loc) · 2.21 KB
/
NELineLabel.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
//
// NELineLabel.swift
// Marco Cancellieri
//
// Created by Marco Cancellieri on 08/03/16.
// Copyright © 2016 Marco Cancellieri. All rights reserved.
//
import UIKit
@IBDesignable
open class NELineLabel: UILabel {
@IBInspectable
open var lineHeight: CGFloat = 1 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable
open var lineSpace: CGFloat = 10 {
didSet {
self.setNeedsDisplay()
}
}
open var lineY: CGFloat {
return self.bounds.midY - self.lineHeight / 2
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
let size = self.intrinsicContentSize
if rect.width > size.width, let ctx = UIGraphicsGetCurrentContext() {
ctx.saveGState()
self.textColor.setFill()
var alignment = textAlignment
if textAlignment == .natural {
alignment = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight ? .left : .right
}
switch alignment {
case .center:
let lineWidth = (rect.width - size.width) / 2 - lineSpace
drawLineLeft(ctx, lineWidth: lineWidth)
drawLineRight(ctx, lineWidth: lineWidth)
case .left, .right:
let lineWidth = rect.width - size.width - lineSpace
alignment == .left ? drawLineRight(ctx, lineWidth: lineWidth) : drawLineLeft(ctx, lineWidth: lineWidth)
default:
debugPrint("\(self.textAlignment) not supported by LineLabel")
}
ctx.restoreGState()
}
}
func drawLineLeft(_ ctx: CGContext, lineWidth: CGFloat) {
let leftRect = lineRect(bounds.minX, lineWidth: lineWidth)
ctx.fill(leftRect)
}
func drawLineRight(_ ctx: CGContext, lineWidth: CGFloat) {
let leftRect = lineRect(bounds.maxX - lineWidth, lineWidth: lineWidth)
ctx.fill(leftRect)
}
func lineRect(_ x: CGFloat, lineWidth: CGFloat) -> CGRect {
return CGRect(x: x, y: self.lineY, width: lineWidth, height: self.lineHeight)
}
}