Symbolic 是一个类型安全的包装器,它构建于 iOS 13 中 Apple 添加的 SF Symbols 字体之上。
它将一个字符串式类型的 API 替换成了一个编译时检查的 API,将 UIImage(systemName: "a.circle.fill")
变成了 UIImage(symbol: Symbolic.Letter.a.rounded.filled)
。
Symbolic 在所有支持的平台(iOS、iPadOS、watchOS 和 tvOS)上都有效,并公开了所有 1,584 个可用的字形,将它们分组为 3 个逻辑命名空间:Letters
、Numbers
和 Symbols
,并为 UIKit
和 SwiftUI
提供了辅助方法。
Symbolic 旨在与 Xcode 11 中新增的 Swift Package Manager 一起使用,有关更多详细信息,请参阅 WWDC 2019 的 在 Xcode 中采用 Swift Packages 会议。
image = UIImage(symbol: Symbolic.Numbers._0) // Basic Symbol
image = UIImage(symbol: Symbolic.Symbols.questionmark.circled) // Circled version of the question mark glyph
image = UIImage(symbol: Symbolic.Symbols.questionmark.video.filled.reversed) // Circled & RTL version of the question mark inside of a camera glyph
image = UIImage(squareSymbol: Symbolic.Letters.f) // Convinience initializer that will automatically select the squared version of the glyph
image = UIImage(filledSymbol: Symbolic.Symbols.sun.haze) // Convinience initializer that will automatically select the filled version of the glyph
除了添加一个类型安全的方法来访问 SF Symbol 字形外,Symbolic 还公开了几个协议,可用于将自定义视图可以包含的符号类型约束到特定子集,例如
FilledSymbol(填充符号)
ReversedSymbol(反向符号)
SquaredSymbol(方形符号)
RoundedSymbol(圆形符号)
可以在下面看到一个示例用例
class CircularButtonCell: UITableViewCell {
typealias CellSymbol = RoundedSymbol & FilledSymbol
var myImage: CellSymbol = Symbolic.Letters.a.rounded.filled {
didSet {
self.imageView?.image = UIImage(symbol: self.myImage)
}
}
func setup(image: CellSymbol) {
self.myImage = image
}
}
class ViewController: UIViewController {
func createCell() {
let cell = CircularButtonCell()
// This cell requires the image to be filled & circular
cell.setup(image: Symbolic.Letters.a.rounded.filled)
// Oh no! This line won't compile!
cell.setup(image: Symbolic.Letters.a.squared.filled)
}
}
Symbolic 由两个目标组成:主框架公开所有字形,以及一个生成器可执行目标,该目标基于 sfsymbols.com 存储库中的数据生成所有具体类型。