AveFontHelpers

一些帮助简化动态字体使用的工具

是什么?

在 iOS 中使用动态字体时,如果想要使用自定义字体、设计或尺寸,有时会很冗长和棘手。您需要使用 UIFontMetrics().scaleFont() 并按照正确的顺序进行操作。如果您想要更改字体的设计或将其缩小一个点,这会变得很烦人。

这个小库提供了一个辅助结构体 Font,可以轻松地将其转换为动态字体。

使用方法

基础是 Font 结构,您可以使用以下参数定义您的字体

您可以这样定义字体

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 的便捷初始化器

UIlabelUITextViewUIButton 都有便捷的辅助方法,它们接受 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. 下也有所有 iOS 文本样式的等效项

let label = UILabel(font: .ios.largeTitle)
let bodyLabel = UILabel(font: .ios.body)
etc