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

时间:2017-11-30 16:07:11

标签: ios swift

我想对我的应用中的所有文字使用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

那么有没有办法配置文本样式的准确程度?

2 个答案:

答案 0 :(得分:1)

One way to get different weights with Dynamic Type is to use other UIFont properties and methods in addition to preferredFont(forTextStyle:).

You can use the pointSize property combined with UIFont.systemFont(ofSize:weight:) to get a different weight:

let title1Font = UIFont.preferredFont(forTextStyle: .title1)
let title1PointSize = title1Font.pointSize
let boldTitle1Font = UIFont.systemFont(ofSize: title1PointSize, weight: .bold)

You can extend UIFont to provide any necessary conveniences. For example, if you need title1 and body styles in various weights, you can create this:

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)
    }

}

Then, accessing various sizes and fonts is super easy:

UIFont.title1.with(weight: .bold)
UIFont.body.with(weight: .semibold)
UIFont.body.with(weight: .light)
UIFont.title1 // normal weight

答案 1 :(得分:0)

快捷键5

通过扩展tktsubota的答案并添加以下内容,您可以将所有字体动态调整为可访问性:

let font = UIFont.largeTitle.with(weight: .bold)
yourLabel.font = UIFontMetrics.default.scaledFont(for: font)
yourLabel.adjustsFontForContentSizeCategory = true

以及tktsubota的UIFont扩展名:

extension UIFont {

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

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

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

}