如何将HTML的CSS添加到NSAttributedString? [英] How to add CSS for HTML to NSAttributedString?

查看:268
本文介绍了如何将HTML的CSS添加到NSAttributedString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 NSAttributedString 加载HTML文件,以便在 UITextView

I am trying to load an HTML file via NSAttributedString to display it in a UITextView.

所以,如何将CSS应用于文本视图的内容?

So, how can I apply CSS to the text view's content?

推荐答案

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

Since iOS 7 you can use NSAttributedString with HTML syntax:

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!

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

You have to add string.html to you project, and the content of the html can be like this:

<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> 

根据我的测试,您可以更改:color,font-family,font-weight,font -size,text-align和use < b> < strong> < i> < u> < sup> ,以及< sub> 代码。

From what I could test, you can change: color, font-family, font-weight, font-size, text-align, and use <b>, <strong>, <i>, <u>, <sup>, and <sub> tags.

这篇关于如何将HTML的CSS添加到NSAttributedString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆