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

Sur*_*gch 13 text-styling dynamic-typing ios textkit swift

我正在使用"使用文本工具包管理iOS应用程序中的文本"教程.它是为Objective C编写的,但我认为无论如何我都会尝试使用Swift.

但是,当我得到以下代码时,我无法弄清楚如何为UITextView使用Swift 设置标题和其他样式.这是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]];
}
Run Code Online (Sandbox Code Playgroud)

我试过了

textView.setFont =
textView.preferredFontForTextStyle =
Run Code Online (Sandbox Code Playgroud)

然而,这些似乎都不起作用,而且我找不到任何Swift答案.

Sur*_*gch 33

本教程有一些代码示例,展示了如何执行此操作.

// 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)
Run Code Online (Sandbox Code Playgroud)

也可以看看