How to use custom font in SwiftUI

Issue #586

In macOS

Add fonts to target. In Info.plist, just need to specify font locations, most of the time they are at Resources folder

ATSApplicationFontsPath (String - macOS) identifies the location of a font file or directory of fonts in the bundle’s Resources directory. If present, macOS activates the fonts at the specified path for use by the bundled app. The fonts are activated only for the bundled app and not for the system as a whole. The path itself should be specified as a relative directory of the bundle’s Resources directory. For example, if a directory of fonts was at the path /Applications/MyApp.app/Contents/Resources/Stuff/MyFonts/, you should specify the string Stuff/MyFonts/ for the value of this key.

1
2
<key>ATSApplicationFontsPath</key>
<string>.</string>

Define font weight as enums, and base on ContentSizeCategory

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
enum OpenSans: String {
case bold = "OpenSans-Bold"
case semiBold = "OpenSans-SemiBold"
case extraBold = "OpenSans-ExtraBold"
case light = "OpenSans-Light"
case regular = "OpenSans-Regular"
}

enum FiraCode: String {
case bold = "FiraCode-Bold"
case medium = "FiraCode-Medium"
case light = "FiraCode-Light"
case regular = "FiraCode-Regular"
case retina = "FiraCode-Retina"
}

extension ContentSizeCategory {
var size: CGFloat {
switch self {
case .small:
return 14
case .medium:
return 16
case .large:
return 20
default:
return 14
}
}
}

extension View {
func customFont(_ font: OpenSans, category: ContentSizeCategory) -> some View {
return self.customFont(font.rawValue, category: category)
}

func customFont(_ name: String, category: ContentSizeCategory) -> some View {
return self.font(.custom(name, size: category.size))
}
}

Then we can specify font weight, thanks to function overloading

1
2
Text("Welcome")
.customFont(OpenSans.bold, category: .large)

In iOS

Observe @Environment(\.sizeCategory) var sizeCategory in ViewModifier

Read more

© 2020 onmyway133 All Rights Reserved.
Theme by hiero