Fonts made easy in iOS — Swift

Sujal Shrestha
2 min readAug 12, 2020

We all use custom fonts in our application. It’s really helpful if you use an extension to easily use fonts throughout your app. Here’s an example:

  1. Define a protocol and a type alias
protocol FontFamily {
var value: String { get }
}
typealias AppFont = UIFont

2. Define an extension to call the AppFont type alias throughout your app

extension AppFont {
static func font(with size: CGFloat, family: FontFamily?) -> AppFont {
guard let family = family,
let requiredFont = UIFont(name: family.value, size: size) else {
return UIFont.systemFont(ofSize: size)
}
return requiredFont
}
}

3. Use enum to handle the different font-weight

enum OpenSans: FontFamily {case regularcase boldcase lightcase semiBoldcase extraBold
var value: String {switch self {case .regular: return "OpenSans-Regular"case .bold: return "OpenSans-Bold"case .light: return "OpenSans-Light"case .semiBold: return "OpenSans-SemiBold"case .extraBold: return "OpenSans-ExtraBold"}}}

4. Finally, call your custom font in any part of your app.

label.font = UIFont.font(with: 16, family: OpenSans.bold)

Note: You need to add your custom fonts inside the project folder and also add it to Info.plist.

--

--