2014-11-15 15 views
0

在iOS 7和8的UITextView中使用調整工作時出現問題。字符串在直接設置字符串或使用NSAttributedString時正常工作我手動構建,但根本不工作,當我從HTML生成NSAttributedString。使用從HTML構建的NSAttributedString在iOS7/8 UITextView中進行調整

下面的代碼將正確克恩文字:

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; 

我在做什麼錯?

回答

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;似乎沒有產生任何影響,所以它可以省略。

相關問題