ios - 使用从 HTML 构建的 NSAttributedString 时在 iOS7/8 UITextView 中进行字距调整

标签 ios nsattributedstring kerning

我无法在 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;

我做错了什么?

最佳答案

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

关于ios - 使用从 HTML 构建的 NSAttributedString 时在 iOS7/8 UITextView 中进行字距调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26945419/

相关文章:

ios - 在 Xcode 中模拟时间流逝

ios - 如何通过 bigcommerce 中的 api 获取隐私政策内容以显示在 iOS 中我的 bigcommerce 商店的移动版本中

objective-c - 如何阻止时间 UILabel 在每次增量时调整大小?

ios - 具有单行文本的 UILabel 的行间距

.net - 修改 System.Drawing.Graphics.DrawString() 中的字距调整

通往 Twitter 的 iOS 标签栏项目

ios - 是否可以使用 NSAttributedString 设置多个字体属性

javascript - 同一个单词中的字符之间是否可以有不同的字母间距?这可以只用 CSS 来完成吗?

java - 在 Java2D 中访问字体字距调整信息

ios - 选择集合中不可见的单元格