SaferFonts
Avoiding potential mistypes while using fonts programatically in Swift
Install / Use
/learn @RuiAAPeres/SaferFontsREADME
Why "Safer"?
Let's imagine we want to set a UILabel's font:
myLabel.font = UIFont(name: "ArialMT", size: 14)!
This approach is error prone and inherently invites for duplication.
- We could easily misspell
"ArialMT"and crash the app. SinceUIFont'sname:size:returns an optional, for practical reasons we would just force unwrap it. (in this particular case it doesn't make sense to use optional binding) - If we need to use the same font in some other place, we might be tempted to just copy/paste it.
SaferFonts, in this case, just bundles the font in a convenient enum:
myLabel.font = UIFont(name: ArialMT.Default.rawValue, size: 14)!
As you might have noticed by now, SaferFont is not a 3rd party library that you can just get using Carthage or Cocopods. It would be a significant burden to use a library with dozens of fonts, when you just need one or two. So instead, this can be viewed as an approach and a database of fonts that you can use.
The Font Protocol
The Font protocol (suggested by renatorodrigues), can also be used to make this enum easier to consume. For example with the font FooBar :
let fooBarFont = UIFont(font: FooBar.Bold, size: 15)
In order to make the enum compliant:
private enum FooBar: String, Font {
case Bold = "FooBar-Bold"
func name() -> String {
return self.rawValue
}
}
ArialMT
enum ArialMT: String {
case Regular = "ArialMT"
case Bold = "Arial-BoldMT"
case Italic = "Arial-ItalicMT"
case BoldItalic = "Arial-BoldItalicMT"
}
HelveticaNeue
enum HelveticaNeue: String {
case Regular = "HelveticaNeue"
case Italic = "HelveticaNeue-Italic"
case Bold = "HelveticaNeue-Bold"
case BoldItalic = "HelveticaNeue-BoldItalic"
case Medium = "HelveticaNeue-Medium"
case MediumItalic = "HelveticaNeue-MediumItalic"
case Light = "HelveticaNeue-Light"
case LightItalic = "HelveticaNeue-LightItalic"
case UltraLight = "HelveticaNeue-UltraLight"
case UltraLightItalic = "HelveticaNeue-UltraLightItalic"
case Thin = "HelveticaNeue-Thin"
case ThinItalic = "HelveticaNeue-ThinItalic"
case CondensedBlack = "HelveticaNeue-CondensedBlack"
case CondensedBold = "HelveticaNeue-CondensedBold"
}
Related Skills
node-connect
344.4kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
99.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
344.4kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
344.4kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
