如何更改动态类型以使用不同的文本样式

Adr*_*ian 5 ios swift dynamic-type-feature

我想用于Dynamic Type我的应用程序中的所有文本。我用的字体是Apple的San Francisco.
我不喜欢默认值,因为它们并不真正用于Bold文本。

以下是所有这些内容的列表:

Style         Weight      Point size    Leading Tracking
--------------------------------------------------------
Large Title   Regular     34pt  41pt    11pt
Title 1       Regular     28pt  34pt    13pt
Title 2       Regular     22pt  28pt    16pt
Title 3       Regular     20pt  25pt    19pt
Headline      Semi-Bold   17pt  22pt.  -24pt
Body          Regular     17pt  22pt.  -24pt
Callout       Regular     16pt  21pt.  -20pt
Subhead       Regular     15pt  20pt.  -16pt
Footnote      Regular     13pt  18pt.  -6pt
Caption 1     Regular     12pt  16pt    0pt
Caption 2     Regular     11pt  13pt    6pt
Run Code Online (Sandbox Code Playgroud)

那么有没有一种方法可以准确地配置文本样式呢?

tkt*_*ota 2

使用动态类型获得不同权重的一种方法是使用UIFont除 之外的其他属性和方法preferredFont(forTextStyle:)

您可以pointSize结合使用该属性UIFont.systemFont(ofSize:weight:)来获得不同的权重:

let title1Font = UIFont.preferredFont(forTextStyle: .title1)
let title1PointSize = title1Font.pointSize
let boldTitle1Font = UIFont.systemFont(ofSize: title1PointSize, weight: .bold)
Run Code Online (Sandbox Code Playgroud)

您可以扩展UIFont以提供任何必要的便利。例如,如果您需要不同重量的样式,您可以创建以下内容title1body

extension UIFont {

    static var title1: UIFont {
        return UIFont.preferredFont(forTextStyle: .title1)
    }
    static var body: UIFont {
        return UIFont.preferredFont(forTextStyle: .body)
    }

    func with(weight: UIFont.Weight) -> UIFont {
        return UIFont.systemFont(ofSize: pointSize, weight: weight)
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,访问各种尺寸和字体非常容易:

UIFont.title1.with(weight: .bold)
UIFont.body.with(weight: .semibold)
UIFont.body.with(weight: .light)
UIFont.title1 // normal weight
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用,它会破坏可访问性,并且当您以编程方式设置字体时,字体不会动态调整。 (2认同)