Suragch Suragch - 7 months ago 22
Swift Question

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

I was working through the Using Text Kit to Manage Text in Your iOS Apps tutorial. It was written for Objective C but I thought I would try to do it anyway using Swift.

However, when I got to the following code I couldn't figure out how to set the heading and other styles for the

UITextView
using Swift. Here is the Objective C code:

- (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]];
}


I tried

textView.setFont =
textView.preferredFontForTextStyle =


Neither of these seemed to work, though, and I couldn't find any Swift answers on SO.

Answer

This tutorial had some code samples that showed how to do it.

@IBOutlet weak var textView: UITextView!

@IBAction func applyHeadlineStyle(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
}
@IBAction func applySubHeadlineStyle(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
}
@IBAction func applyBodyStyle(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
}
@IBAction func applyFootnoteStyle(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote)
}
@IBAction func applyCaption1Style(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
}
@IBAction func applyCaption2Style(sender: AnyObject) {

    textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
}

See also

Comments