如何在Swift中设置动态类型文本样式的标题、副标题、正文、脚注和说明字体?

20

我正在学习使用Text Kit来管理iOS应用中的文本的教程《使用 Text Kit 管理 iOS 应用中的文本》。原教程是用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 =

不过,这两种方法似乎都没用,并且我在Stack Overflow上也找不到任何Swift的答案。


Xcode会自动为您完成它。开始编写,然后按Esc键。试一试。 - Leo Dabus
我的问题是setFontpreferredFontForTextStyle不是UITextView的方法或属性,所以没有自动完成。我只是猜测。不过我在另一个网站上找到了解决方案。 - Suragch
1
你会注意到很多方法并没有使用“set”这个词,因为它并不是必需的。尝试在不使用“set”的情况下进行操作。 - Leo Dabus
1个回答

49

这篇教程提供了一些代码示例,展示了如何完成该操作。

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

另请参阅


如何撤销设置的样式。 - H Raval

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接