2

Sorry for a basic question, but I'm not sure where to start. Is the following possible in Swift?

In a UITextView (Not a label, as in the possible duplicate), different bits of text having different formatting: for instance, a line of large text in the same UITextView as a line of small text. Here is a mockup of what I mean: enter image description here

Is this possible in one UITextView?

Community
  • 1
  • 1
rocket101
  • 7,369
  • 11
  • 45
  • 64
  • 1
    possible duplicate of [Use multiple font colors in a single label - Swift](http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift) – Thilo Apr 15 '15 at 00:31
  • @Thilo I don't think it's a duplicate: the question you referenced is about labels, not text views. – rocket101 Apr 15 '15 at 00:34

1 Answers1

3

You should have a look at NSAttributedString. Here's an example of how you could use it:

    let largeTextString = "Here is some large, bold text"
    let smallTextString = "Here is some smaller text"

    let textString = "\n\(largeTextString)\n\n\(smallTextString)"
    let attrText = NSMutableAttributedString(string: textString)

    let largeFont = UIFont(name: "Arial-BoldMT", size: 50.0)!
    let smallFont = UIFont(name: "Arial", size: 30.0)!

    //  Convert textString to NSString because attrText.addAttribute takes an NSRange.
    let largeTextRange = (textString as NSString).range(of: largeTextString)
    let smallTextRange = (textString as NSString).range(of: smallTextString)

    attrText.addAttribute(NSFontAttributeName, value: largeFont, range: largeTextRange)
    attrText.addAttribute(NSFontAttributeName, value: smallFont, range: smallTextRange)

    textView.attributedText = attrText

The result:

enter image description here

Community
  • 1
  • 1
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78