-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathScaledFont.swift
More file actions
82 lines (68 loc) · 2.26 KB
/
ScaledFont.swift
File metadata and controls
82 lines (68 loc) · 2.26 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
72
73
74
75
76
77
78
79
80
81
82
import SwiftUI
import AppKit
// MARK: built-in fonts
// Refer to https://developer.apple.com/design/human-interface-guidelines/typography#macOS-built-in-text-styles
extension Font {
public var builtinSize: CGFloat {
let textStyle = nsTextStyle ?? .body
return NSFont.preferredFont(forTextStyle: textStyle).pointSize
}
// Map SwiftUI Font to NSFont.TextStyle
private var nsTextStyle: NSFont.TextStyle? {
switch self {
case .largeTitle: .largeTitle
case .title: .title1
case .title2: .title2
case .title3: .title3
case .headline: .headline
case .subheadline: .subheadline
case .body: .body
case .callout: .callout
case .footnote: .footnote
case .caption: .caption1
case .caption2: .caption2
default: nil
}
}
var builtinWeight: Font.Weight {
switch self {
case .headline: .bold
case .caption2: .medium
default: .regular
}
}
}
public extension View {
func scaledFont(_ font: Font) -> some View {
ScaledFontView(self, font: font)
}
func scaledFont(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) -> some View {
ScaledFontView(self, size: size, weight: weight, design: design)
}
}
public struct ScaledFontView<Content: View>: View {
let fontSize: CGFloat
let fontWeight: Font.Weight
var fontDesign: Font.Design
let content: Content
@StateObject private var fontScaleManager = FontScaleManager.shared
var fontScale: Double {
fontScaleManager.currentScale
}
init(_ content: Content, font: Font) {
self.fontSize = font.builtinSize
self.fontWeight = font.builtinWeight
self.fontDesign = .default
self.content = content
}
public init(_ content: Content, size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) {
self.fontSize = size
self.fontWeight = weight
self.fontDesign = design
self.content = content
}
public var body: some View {
content
.font(.system(size: fontSize * fontScale, weight: fontWeight, design: fontDesign))
}
}