Swift 不同格式的 UITextView

Swift UITextView with different formatting

很抱歉提出一个基本问题,但我不确定从哪里开始。在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:

这在一个 UITextView 中可行吗?

你应该看看 NSAttributedString。以下是如何使用它的示例:

    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

结果: