20

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • Xcode auto completes it for you. Start writing it and then press escape. Give it a try. – Leo Dabus Feb 26 '15 at 06:18
  • My problem was that `setFont` and `preferredFontForTextStyle` are not methods or properties of `UITextView` so there was nothing to autocomplete. I was just guessing. I did find a solution on another website though. – Suragch Feb 26 '15 at 06:30
  • 1
    You will notice a lot of methods just don't have the word set as it is not necessary try it always without "set" – Leo Dabus Feb 26 '15 at 06:42

1 Answers1

49

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

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

See also

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393