ios 在 uitextview 中显示 html 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2454067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:00:11  来源:igfitidea点击:

Display html text in uitextview

iosiphoneuitextview

提问by milanjansari

How can I display HTML text in textview?

如何在 textview 中显示 HTML 文本?

For example,

例如,

string <h1>Krupal testing <span style="font-weight:
bold;">Customer WYWO</span></h1>

Suppose text is bold so it display in textview as bold string but I want display normal text. Is this possible in the iPhone SDK?

假设文本是粗体,所以它在 textview 中显示为粗体字符串,但我想显示普通文本。这在 iPhone SDK 中是可能的吗?

采纳答案by kennytm

Use a UIWebView on iOS 5-.

在 iOS 5- 上使用 UIWebView。

On iOS 6+ you can use UITextView.attributedString, see https://stackoverflow.com/a/20996085for how.

在iOS 6+您可以使用UITextView.attributedString,请参阅https://stackoverflow.com/a/20996085如何。



There's also an undocumented-[UITextView setContentToHTMLString:]method. Do not use this if you want to submit to AppStore.

还有一个未记录的-[UITextView setContentToHTMLString:]方法。如果您想提交到 AppStore,请不要使用它。

回答by Bhoopi

Use following block of code for ios 7+.

对 ios 7+ 使用以下代码块。

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
    documentAttributes: nil
                 error: nil
];
textView.attributedText = attributedString;

回答by pableiros

For Swift 4, Swift 4.2:and Swift 5

对于Swift 4Swift 4.2:Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

For Swift 3:

对于Swift 3

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

回答by David

BHUPI's answer is correct, but if you would like to combine your custom font from UILabel or UITextView with HTML content, you need to correct your html a bit:

BHUPI 的回答是正确的,但是如果您想将 UILabel 或 UITextView 中的自定义字体与 HTML 内容结合起来,则需要稍微更正您的 html:

NSString *htmlString = @"<b>Bold</b><br><i>Italic</i><p> <del>Deleted</del><p>List<ul><li>Coffee</li><li type='square'>Tea</li></ul><br><a href='URL'>Link </a>";

htmlString = [htmlString stringByAppendingString:@"<style>body{font-family:'YOUR_FONT_HERE'; font-size:'SIZE';}</style>"];
/*Example:

 htmlString = [htmlString stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",_myLabel.font.fontName,_myLabel.font.pointSize]];
*/
 NSAttributedString *attributedString = [[NSAttributedString alloc]
                      initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                documentAttributes: nil
                             error: nil
            ];
textView.attributedText = attributedString;

You can see the difference on the picture below: enter image description here

您可以在下图中看到不同之处: 在此处输入图片说明

回答by sElanthiraiyan

You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

您可以查看 OHAttributedLabel 类,我使用这些类来解决 textField 的此类问题。在这里,他们重写了 drawRect 方法以获得所需的样式。

https://github.com/AliSoftware/OHAttributedLabel

https://github.com/AliSoftware/OHAttributedLabel

回答by Justin

My first response was made before iOS 7 introduced explicit support for displaying attributed strings in common controls. You may now set attributedTextof UITextViewto an NSAttributedStringcreated from HTML content using:

我的第一个反应是在 iOS 7 引入对在公共控件中显示属性字符串的明确支持之前做出的。现在,您可以设置attributedTextUITextView一个NSAttributedString使用HTML创建内容:

-(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error 

- initWithData:options:documentAttributes:error: (Apple Doc)

- initWithData:options:documentAttributes:error: (Apple Doc)

Original answer, preserved for history:

原始答案,为历史保留:

Unless you use a UIWebView, your solution will rely directly on CoreText. As ElanthiraiyanS points out, some open source projects have emerged to simplify rich text rendering. I would recommend NSAttributedString-Additions-For-HTML(Edit:the project has been supplanted DTCoreText), which features classes to generate and display attributed strings from HTML.

除非您使用UIWebView,否则您的解决方案将直接依赖于CoreText. 正如 ElanthiraiyanS 指出的那样,一些开源项目已经出现以简化富文本渲染。我会推荐NSAttributedString-Additions-For-HTML编辑:该项目已被DTCoreText取代),它具有从 HTML 生成和显示属性字符串的类。

回答by u5150587

Answer has fitted to me that from BHUPI.

BHUPI 的答案很适合我。

The code transfer to swift as below:

代码转移到swift如下:

Pay attention "allowLossyConversion: false"

注意“allowLossyConversion:false”

if you set the value to true, it will show pure text.

如果您将该值设置为 true,它将显示纯文本。

let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

        let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

        UITextView_Message.attributedText = theAttributedString

回答by Ajay Iyer

For Swift3

对于 Swift3

    let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

    let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)

    UITextView_Message.attributedText = theAttributedString

回答by HotJard

For some cases UIWebView is a good solution. Because:

在某些情况下 UIWebView 是一个很好的解决方案。因为:

  • it displays tables, images, other files
  • it's fast (comparing with NSAttributedString: NSHTMLTextDocumentType)
  • it's out of the box
  • 它显示表格、图像、其他文件
  • 它很快(与 NSAttributedString 相比:NSHTMLTextDocumentType)
  • 它是开箱即用的

Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)

使用 NSAttributedString 会导致崩溃,如果 html 很复杂或包含表格(例如

For loading text to web view you can use the following snippet (just example):

要将文本加载到 Web 视图,您可以使用以下代码段(仅作为示例):

func loadHTMLText(_ text: String?, font: UIFont) {
        let fontSize = font.pointSize * UIScreen.screens[0].scale
        let html = """
        <html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
        """
        self.loadHTMLString(html, baseURL: nil)
    }

回答by Dip Dhingani

You can also use one more way. Three20 library offers a method through which we can construct a styled textView. You can get the library here: http://github.com/facebook/three20/

您还可以使用另一种方式。Three20 库提供了一种方法,通过它我们可以构建样式化的 textView。你可以在这里得到图书馆:http: //github.com/facebook/three20/

The class TTStyledTextLabel has a method called textFromXHTML: I guess this would serve the purpose. But it would be possible in readonly mode. I don't think it will allow to write or edit HTML content.

类 TTStyledTextLabel 有一个名为 textFromXHTML 的方法:我想这可以达到目的。但是在只读模式下是可能的。我认为它不允许编写或编辑 HTML 内容。

There is also a question which can help you regarding this: HTML String content for UILabel and TextView

还有一个问题可以帮助您解决这个问题:UILabel 和 TextView 的 HTML 字符串内容

I hope its helpful.

我希望它有帮助。