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