优雅的使用 Iconfont

Jan 11, 2021 • 预计阅读时间 1 分钟

Iconfont 就是把矢量图作为字体,可以很方便的在 App 里显示图标。拥有体积小加载速度快的优点。

推荐两个生成 Iconfont 的网站:

Fontello 没有自己的资源库,网站提供的素材是第三方的,基本上来自于 Fontelico 和 Font Awesome 。

Iconfont 是阿里的矢量图标库,素材由国内众多的设计师提供,资源非常丰富而且还有搜索功能。

使用 Iconfont

把生成的字体文件(ttf)作为文件资源添加到 App 里,一般放在后缀为 .bundle 项目的目录里面。

使用字体前,先注册字体文件:

let fontURL = URL(fileURLWithPath: path)
CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, nil)

如果是在 fontello 生成的 Iconfont,字体名称是 fontello,注册以后就可以通过字体的名称使用字体了。

系统在渲染文字的时候会根据 UIFont 里的 cascadeList 按顺序选择字体。

可以利用这个特性让数字、字母和 CJK 字符分别使用不同的字体渲染,和 CSS 里指定 font-family 效果一样。

要优雅的显示 Iconfont,只需要在 cascadeList 里加上 Iconfont 的字体就可以了,系统渲染字体时就会自动 fallback 到 Iconfont 字体中。

extension UIFont {

    public class func iconFont(ofSize size: CGFloat) -> UIFont {
        let cascadeList = [UIFontDescriptor(fontAttributes: [.name: iconFontName])]
        let cascadedFontDescriptor = UIFont.systemFont(ofSize: size).fontDescriptor.addingAttributes([.cascadeList: cascadeList])
        let cascadedFont = UIFont(descriptor: cascadedFontDescriptor, size: size)

        return cascadedFont
    }
}

参考资料

Creating Apps for a Global Audience

Common assumptions can break when your app is used by a global audience. Learn about the many aspects of creating apps for different regions and languages. Understand how to use fonts and typography, layout techniques, and support text input so your app shines in all languages.

https://developer.apple.com/videos/play/wwdc2018/201/

iOSSwift
版权声明:如果转发请带上本文链接和注明来源。

lvv.me

iOS/macOS Developer

iOS Simulators

xcrun 使用说明