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

时间:2015-02-26 06:01:19

标签: ios swift dynamic-typing textkit text-styling

我正在完成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 =

但这些似乎都没有用,而且我找不到任何关于Swift的答案。

1 个答案:

答案 0 :(得分:28)

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)

另见