I am having trouble getting kerning to work inside a UITextView on iOS 7 and 8. The kerning works fine when I set the string directly, or when I use an NSAttributedString that I construct manually, but simply doesn't work when I generate the NSAttributedString from HTML.
The following code will kern the text correctly:
self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Test"];
But the following does not:
NSString *html = @"<html><head><style>\
body { font-size: 40px; text-rendering: optimizeLegibility; }\
</style></head>\
<body>Test</body></html>";
NSAttributedString *attrString = [[NSAttributedString alloc]
initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
options:@{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
}
documentAttributes:nil error:nil];
self.textView.attributedText = attrString;
What am I doing wrong?
When generating an
NSAttributedString
and theNSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
option is set, iOS adds anNSKern = 0
attribute to the attributed string. You can inspect this by simply logging the attributed string:To resolve the issue, simply remove the NSKern property altogether:
Note that the
text-rendering: optimizeLegibility;
does not appear to have any impact, so it can be ommitted.