let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .body) label.adjustsFontForContentSizeCategory = true设置 adjustsFontForContentSizeCategory 为 true,可以在设备的内容大小类别更改时自动更新字体。上面的代码将返回一个苹果 San Francisco 常规字体,大小为 17(大文本尺寸下的 body 样式),以下是大文本大小上的所有文本样式的示例。
let customFont = UIFont(name: "Merriweather-Regular", size: 17)! // <1> let label = UILabel() // 堆代码 duidaima.com label.adjustsFontForContentSizeCategory = true label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: customFont) // <2><1> 我们初始化了自定义字体。在这个例子中,我使用了 Google 字体的 Merriweather 字体。
let customFonts: [UIFont.TextStyle: UIFont] = [ .largeTitle: UIFont(name: "Merriweather-Regular", size: 34)!, .title1: UIFont(name: "Merriweather-Regular", size: 28)!, .title2: UIFont(name: "Merriweather-Regular", size: 22)!, .title3: UIFont(name: "Merriweather-Regular", size: 20)!, .headline: UIFont(name: "Merriweather-Bold", size: 17)!, .body: UIFont(name: "Merriweather-Regular", size: 17)!, .callout: UIFont(name: "Merriweather-Regular", size: 16)!, .subheadline: UIFont(name: "Merriweather-Regular", size: 15)!, .footnote: UIFont(name: "Merriweather-Regular", size: 13)!, .caption1: UIFont(name: "Merriweather-Regular", size: 12)!, .caption2: UIFont(name: "Merriweather-Regular", size: 11)! ] extension UIFont { class func customFont(forTextStyle style: UIFont.TextStyle) -> UIFont { let customFont = customFonts[style]! let metrics = UIFontMetrics(forTextStyle: style) let scaledFont = metrics.scaledFont(for: customFont) return scaledFont } }将 UIFontMetrics(forTextStyle: style).scaledFont(for: customFont) 替换为 UIFont.customFont(forTextStyle: style) 并再次运行即可。
let styles: [UIFont.TextStyle] = [.largeTitle, .title1, .title2, .title3, .headline, .subheadline, .body, .callout, .footnote, .caption1, .caption2] for style in styles { ... let label = UILabel() label.adjustsFontForContentSizeCategory = true label.text = String(describing: style) label.font = UIFont.customFont(forTextStyle: style) ... }最后看下效果:
结论