rocket101
rocket101

Reputation: 7537

Swift UITextView with different formatting

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?

Upvotes: 2

Views: 2828

Answers (1)

ABakerSmith
ABakerSmith

Reputation: 22969

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

Upvotes: 3

Related Questions