动态加载字体
在一些阅读类的应用中,可能会有更换字体的需求。常规的字体更换是将字体文件添加到项目中,并在 Info.plist
文件中添加好参数。此处的字体添加方式为从服务器下载字体并添加,不用设置 Info.plist
。
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
| import CoreGraphics import CoreText
...
func loadFont(_ fontName: String, size: CGFloat = 14) -> UIFont? { var result: UIFont? defer { return result } guard let path = Bundle.main.path(forResource: fontName, ofType: "ttf") else { return } guard let data = NSData(contentsOfFile: path), let fontData = data as? CFData else { return }
guard let fontDataProvider = CGDataProvider(data: fontData) else { return } guard let fontRef = CGFont(fontDataProvider) else { return }
var error = Unmanaged<CFError>?(nilLiteral: ()) CTFontManagerRegisterGraphicsFont(fontRef, &error)
guard let realFontName = fontRef.fullName as? String else { return } guard let font = UIFont(name: realFontName, size: size) else { return } result = font }
|