我无法在iOS 7和8上的UITextView中进行字距调整。当我直接设置字符串时,或者当我使用我手动构建的NSAttributedString时,字距调整工作正常,但是当我使用时根本不起作用从HTML生成NSAttributedString。
以下代码将正确理解文本:
self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Test"];
但以下情况并非如此:
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;
我做错了什么?
答案 0 :(得分:1)
生成NSAttributedString
并设置NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
选项后,iOS会为属性字符串添加NSKern = 0
属性。您只需记录属性字符串即可检查:
Test{
NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
NSFont = "<UICTFont: 0x7fa470451e90> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 40.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
NSStrokeWidth = 0;
}
要解决此问题,只需完全删除NSKern属性:
NSMutableAttributedString *mutableAttributedString = [attrString mutableCopy];
[mutableAttributedString removeAttribute:NSKernAttributeName
range:NSMakeRange(0, [mutableAttrString length])];
请注意,text-rendering: optimizeLegibility;
似乎没有任何影响,因此可以省略。