一些帮助简化动态字体使用的工具
在 iOS 中使用动态字体时,如果想要使用自定义字体、设计或尺寸,有时会很冗长和棘手。您需要使用 UIFontMetrics().scaleFont()
并按照正确的顺序进行操作。如果您想要更改字体的设计或将其缩小一个点,这会变得很烦人。
这个小库提供了一个辅助结构体 Font
,可以轻松地将其转换为动态字体。
基础是 Font
结构,您可以使用以下参数定义您的字体
size
:以磅为单位的尺寸maximumSize
:可选字体的最大尺寸style
:可选此字体基于的文本样式,用于缩放。如果 size = 0,将使用 iOS 文本样式的磅值尺寸weight
:可选字体的粗细design
:可选字体的设计,例如 .rounded
traits
:可选字体的特性,例如 .italic
scalability
:可选,.fixed
、.scalable
或 .placeholder
。固定和占位符字体不会动态缩放name
:可选要使用的字体系列名称,如果为 nil,将使用系统字体您可以这样定义字体
extension Font {
// we want a thinner large title
let largeTitle = Font(style: .largeTitle, weight: .thin)
// our custom body font, scales as the iOS body font
let body = Font(size: 14, style: .body)
// our custom button font, with a maximum size
let button = Font(size: 13, maximumSize: 26, weight: .bold)
// a tab bar font that doesn't scale
let tabBarItem = Font(size: 11, scalalability: .fixed)
let tabBarItem2 = Font.fixed(size: 12)
}
/// there are convenience inits() for UILabel, UITextView and UIButton
let label = UILabel(font: .largeTitle)
// assigning a font can be done the .from() or
let bodyLabel = UILabel()
bodyLabel.font = .from(body)
bodyLabel.font = Font.body.font()
要将这些项目转换为 UIFont
,请调用 .from(.largeTitle)
或 Font.largeTitle.font()
UIlabel
、UITextView
和 UIButton
都有便捷的辅助方法,它们接受 Font
并在需要时自动启用动态字体
let label = UILabel(text: "Some Text", font: .largeTitle, color: label, alignment: .center)
let textView = UITextView(font: .body, color: .secondaryLabel)
let button = UIButton(font: .button.smaller.rounded)
有很多修饰符可用于组合字体,其中一些如下例所示
let body = Font(size: 14, style: .body)
body.smaller // 1pt smaller
body.smaller(by: 5) // 5 pts smaller
body.larger // 1pt larger
body.larger(by: 5) // 5 pts larger
body.with(size: 12) // same font, but with size 12
body.with(weight: .bold) // same font, but bold
body.with(design: .rounded) // same font, but rounded
body.with(scalability: .fixed) // same font, but not scalable
body.with(traits: .italic) // same font, but italic only
body.bold.adding(traits: .italic) // same font, but italic and bold
body.bolder // a bolder font
body.rounded // a rounded font
body.thin // a thin font
body.italic // an italic font
body.fixed // a font that doesn't scale
在 .ios.
下也有所有 iOS 文本样式的等效项
let label = UILabel(font: .ios.largeTitle)
let bodyLabel = UILabel(font: .ios.body)
etc