HTML Attributed Strings change underlying font on UITextView/UILabel

Originator:ahartwell
Number:rdar://FB7613296 Date Originated:March 4, 2020
Status:Open Resolved:
Product:UIKit Product Version:
Classification: Reproducible:Always
 
When displaying HTML in a UITextView/UILabel if the document ends in a tag `</b>` or `</i>` the fontDescriptor on the font on the underlying label changes. But if there is a blank character, or a character not wrapped in an html tag, the font is unchanged.


Playground that recreates the issue

```
import UIKit

var htmlChangesFont = "<i>Testing Test</i>"
var htmlDoesntChangeFont = "<i>Testing Test</i> "

let textView = UITextView()
textView.font = UIFont.systemFont(ofSize: 12)
print(textView.font!.fontDescriptor)
/*
Prints out:
 UICTFontDescriptor <0x600001881020> = {
     NSCTFontUIUsageAttribute = CTFontRegularUsage;
     NSFontSizeAttribute = 12;
 }
*/

let data = html.data(using: .utf8)!

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue),
]


let attributedString = try? NSMutableAttributedString(data: data, options: options,
                                                      documentAttributes: nil)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center

let range = NSRange(location: 0, length: attributedString?.length ?? 0)
attributedString?.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)

textView.attributedText = attributedString
print(textView.font!.fontDescriptor)
/*
Prints out:
 UICTFontDescriptor <0x6000018950e0> = {
     NSFontNameAttribute = "TimesNewRomanPS-ItalicMT";
     NSFontSizeAttribute = 12;
 }
*/
```

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!