如何在Swift中为动态类型文本样式设置标题、副标题、body、脚注和字幕字体?

How to set heading, subheading, body, footnote, and captions font for dynamic type text styles in Swift?

我正在学习 Using Text Kit to Manage Text in Your iOS Apps 教程。它是为 Objective C 编写的,但我想无论如何我都会尝试使用 Swift.

来完成它

但是,当我看到下面的代码时,我不知道如何使用 Swift 为 UITextView 设置标题和其他样式。这是 Objective C 代码:

- (IBAction)applyHeadlineStyle:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]];
}

- (IBAction)applySubHeadlineStyle:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]];
}

- (IBAction)applyBodyStyle:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
}

- (IBAction)applyFootnoteStyle:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
}

- (IBAction)applyCaption1Style:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]];
}

- (IBAction)applyCaption2Style:(id)sender {
    [_textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleCaption2]];
}

我试过了

textView.setFont =
textView.preferredFontForTextStyle =

不过,这些似乎都不起作用,而且我在 SO 上找不到任何 Swift 答案。

This tutorial 有一些代码示例展示了如何做到这一点。

// headline
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)

// subheadline
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline)

// body
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)

// footnote
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.footnote)

// caption 1
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.caption1)

// caption 2
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.caption2)

另见

  • Setting the font programmatically