如何将HTML的CSS添加到NSAttributedString?

Kar*_*gat 13 uitextview nsattributedstring ios7

我试图通过NSAttributedString加载HTML文件,以在UITextView中显示它.

那么,我如何将CSS应用于文本视图的内容?

And*_*ues 29

从iOS 7开始,您可以使用NSAttributedStringHTML语法:

NSURL *htmlString = [[NSBundle mainBundle]  URLForResource: @"string"     withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
                                                                                       options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                            documentAttributes:nil
                                                                                         error:nil];
textView.attributedText = stringWithHTMLAttributes; // attributedText field!
Run Code Online (Sandbox Code Playgroud)

您必须将string.html添加到项目中,并且html的内容可以是这样的:

<html>
  <head>
    <style type="text/css">
      body {
        font-size: 15px;
        font-family: Avenir, Arial, sans-serif;
        color: red;
      }
    </style>
  </head>
  <body>
    <p>This is the text</p>
  </body>
</html> 
Run Code Online (Sandbox Code Playgroud)

从我可以测试,您可以更改:颜色,字体家庭,字体重量,字体大小,文本对齐,和使用<b>,<strong>,<i>,<u>,<sup>,和<sub>标签.