-
Notifications
You must be signed in to change notification settings - Fork 115
/
LabelStyle.swift
80 lines (67 loc) · 2.48 KB
/
LabelStyle.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
//
// The code generated using FigmaExport — Command line utility to export
// colors, typography, icons and images from Figma to Xcode project.
//
// https://github.com/RedMadRobot/figma-export
//
// Don’t edit this code manually to avoid runtime crashes
//
import UIKit
public struct LabelStyle {
enum TextCase {
case uppercased
case lowercased
case original
}
let font: UIFont
let fontMetrics: UIFontMetrics?
let lineHeight: CGFloat?
let tracking: CGFloat
let textCase: TextCase
init(font: UIFont, fontMetrics: UIFontMetrics? = nil, lineHeight: CGFloat? = nil, tracking: CGFloat = 0, textCase: TextCase = .original) {
self.font = font
self.fontMetrics = fontMetrics
self.lineHeight = lineHeight
self.tracking = tracking
self.textCase = textCase
}
public func attributes(
for alignment: NSTextAlignment = .left,
lineBreakMode: NSLineBreakMode = .byTruncatingTail
) -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
paragraphStyle.lineBreakMode = lineBreakMode
var baselineOffset: CGFloat = .zero
if let lineHeight {
let scaledLineHeight: CGFloat = fontMetrics?.scaledValue(for: lineHeight) ?? lineHeight
paragraphStyle.minimumLineHeight = scaledLineHeight
paragraphStyle.maximumLineHeight = scaledLineHeight
baselineOffset = (scaledLineHeight - font.lineHeight) / 4.0
}
return [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.kern: tracking,
NSAttributedString.Key.baselineOffset: baselineOffset,
NSAttributedString.Key.font: font
]
}
public func attributedString(
from string: String,
alignment: NSTextAlignment = .left,
lineBreakMode: NSLineBreakMode = .byTruncatingTail
) -> NSAttributedString {
let attributes = attributes(for: alignment, lineBreakMode: lineBreakMode)
return NSAttributedString(string: convertText(string), attributes: attributes)
}
private func convertText(_ text: String) -> String {
switch textCase {
case .uppercased:
return text.uppercased()
case .lowercased:
return text.lowercased()
default:
return text
}
}
}