-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNitroTextImpl+Font.swift
More file actions
71 lines (66 loc) · 2.15 KB
/
NitroTextImpl+Font.swift
File metadata and controls
71 lines (66 loc) · 2.15 KB
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
//
// NitroTextImpl+Font.swift
// Pods
//
// Font-related helpers for NitroTextImpl.
//
import UIKit
struct FontKey: Hashable {
let size: CGFloat
let weightRaw: CGFloat
let italic: Bool
}
extension NitroTextImpl {
func makeFont(for fragment: Fragment, defaultPointSize: CGFloat?) -> (value: UIFont, isItalic: Bool) {
let resolvedSize: CGFloat = {
if let s = fragment.fontSize { return CGFloat(s) }
if let current = defaultPointSize { return current }
return 14.0
}()
let weightToken = fragment.fontWeight ?? FontWeight.normal
let uiWeight = Self.uiFontWeight(for: weightToken)
let isItalic = fragment.fontStyle == FontStyle.italic
let key = FontKey(size: resolvedSize, weightRaw: uiWeight.rawValue, italic: isItalic)
if let cached = fontCache[key] {
return (cached, isItalic)
}
var base = UIFont.systemFont(ofSize: resolvedSize, weight: uiWeight)
if isItalic {
var traits = base.fontDescriptor.symbolicTraits
traits.insert(.traitItalic)
if let italicDesc = base.fontDescriptor.withSymbolicTraits(traits) {
let traitsDict: [UIFontDescriptor.TraitKey: Any] = [.weight: uiWeight]
let finalDesc = italicDesc.addingAttributes([
UIFontDescriptor.AttributeName.traits: traitsDict
])
base = UIFont(descriptor: finalDesc, size: resolvedSize)
}
}
fontCache[key] = base
return (base, isItalic)
}
static func uiFontWeight(for weight: FontWeight) -> UIFont.Weight {
switch weight {
case .ultralight:
return .ultraLight
case .thin:
return .thin
case .light:
return .light
case .regular:
return .regular
case .medium:
return .medium
case .semibold:
return .semibold
case .bold:
return .bold
case .heavy:
return .heavy
case .black:
return .black
default:
return .regular
}
}
}