0

我无法在 iOS 7 和 8 上的 UITextView 内进行字距调整。当我直接设置字符串或使用手动构造的 NSAttributedString 时,字距调整工作正常,但在生成 NSAttributedString来自 HTML。

以下代码将正确调整文本:

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;

我究竟做错了什么?

4

1 回答 1

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;似乎没有任何影响,因此可以省略。

于 2014-11-15T11:41:59.043 回答