在 UILabel iphone 中显示 HTML 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15872257/
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-29 07:20:34  来源:igfitidea点击:

Display HTML text in UILabel iphone

htmlxcodetextuilabel

提问by Khushboo

I am getting a HTML Response from a webservice Below is the HTML I am getting in response

我收到来自网络服务的 HTML 响应 下面是我收到的 HTML 响应

<p><strong>Topic</strong>Gud mrng.</p>
\n<p><strong>Hello Everybody</strong>: How are you.</p>
\n<p><strong>I am fine</strong>: 1 what about you.</p>

I need to display the text in UILabel.

我需要在 UILabel 中显示文本。

Please help

请帮忙

采纳答案by Swati

Use RTLabel library to convert the HTML text. I have used it several times. It works. Here is link to the library and a sample code.

使用 RTLabel 库转换 HTML 文本。我已经用过几次了。有用。这是库的链接和示例代码。

https://github.com/honcheng/RTLabel.

https://github.com/honcheng/RTLabel

Hope I helped.

希望我有所帮助。

回答by Paul Cantrell

You can do it without any third-party libraries by using attributed text. I believe it does accept HTML fragments, like the one you're getting, but you may want to wrap it in a complete HTML document so that you can specify CSS:

您可以使用属性文本在没有任何第三方库的情况下完成此操作。我相信它确实接受 HTML 片段,就像你得到的那样,但你可能想把它包装在一个完整的 HTML 文档中,以便你可以指定 CSS:

static NSString *html =
    @"<html>"
     "  <head>"
     "    <style type='text/css'>"
     "      body { font: 16pt 'Gill Sans'; color: #1a004b; }"
     "      i { color: #822; }"
     "    </style>"
     "  </head>"
     "  <body>Here is some <i>formatting!</i></body>"
     "</html>";

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
NSError *err = nil;
label.attributedText =
    [[NSAttributedString alloc]
              initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                   options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
        documentAttributes: nil
                     error: &err];
if(err)
    NSLog(@"Unable to parse label text: %@", err);

Not concise, but you can mop up the mess by adding a category to UILabel:

不简洁,但您可以通过向 UILabel 添加类别来清理混乱:

@implementation UILabel (Html)

- (void) setHtml: (NSString*) html
    {
    NSError *err = nil;
    self.attributedText =
        [[NSAttributedString alloc]
                  initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                       options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
            documentAttributes: nil
                         error: &err];
    if(err)
        NSLog(@"Unable to parse label text: %@", err);
    }

@end

[someLabel setHtml:@"Be <b>bold!</b>"];

回答by Oliver White

Swift 4: version

斯威夫特 4:版本

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil) else { return nil }
        return html
    }
}

Swift 3: version

斯威夫特 3:版本

extension String {
func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }
    return html
    }
}

Swift 2: version

斯威夫特 2:版本

extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
            guard let html = try? NSMutableAttributedString(
              data: data, 
              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
              documentAttributes: nil) else { return nil }
            return html
        }
}

use it as:

将其用作:

label.attributedText = yourStringVar.htmlAttributedString()

回答by Paul B

Swift 4

斯威夫特 4

I would rather suggest to extend NSAttributedString with failable convenience init. Stringis not responsible for making NSAttributedStringby it's nature.

我宁愿建议使用可失败的便利初始化来扩展 NSAttributedString。String不负责制作NSAttributedString的性质。

extension NSAttributedString {
     convenience init?(html: String) {
        guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
            return nil
        }
        guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString: attributedString)
    }
}
label.attributedText = NSAttributedString(html: "<span> Some <b>bold</b> and <a href='#/userProfile/uname'> Hyperlink </a> and so on </span>")

回答by Chirag Pipaliya

From: https://stackoverflow.com/a/5581178/237838

来自:https: //stackoverflow.com/a/5581178/237838



To convert HTML to plain text DownloadFile

将 HTML 转换为纯文本下载文件

and use

并使用

stringByConvertingHTMLToPlainTextfunction on your NSString

stringByConvertingHTMLToPlainText在您的功能 NSString



OR

或者

You can use DTCoreText(previously known as NSAttributedString Additions for HTML).

您可以使用DTCoreText(以前称为 HTML 的 NSAttributedString Additions)。

回答by Beninho85

Here is the swift 2 version:

这是 swift 2 版本:

    let htmlStringData = NSString(string: "<strong>Your HTML String here</strong>").dataUsingEncoding(NSUTF8StringEncoding)
    guard let html = htmlStringData else { return }

    do {
        let htmlAttrString = try NSAttributedString(data: html, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        yourLabel.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }

回答by NSnik

The above answer in Swift 3:

Swift 3 中的上述答案:

    var str = "<html> ... some html ... </html>"

    let htmlStringData = NSString(string: str).data(using: String.Encoding.utf8.rawValue)
    let html = htmlStringData

    do {
        let htmlAttrString = try? NSAttributedString(
                data: html!,
                options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: nil
        )
        agreementText.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }

回答by Mr.Javed Multani

Sometimes we need to display HTML content on the screen by using UILabel. How to display the HTML content in UILabel we see that in this article. let's start and achieve it.

有时我们需要使用 UILabel 在屏幕上显示 HTML 内容。如何在 UILabel 中显示 HTML 内容我们在这篇文章中看到了。让我们开始并实现它。

enter image description here

enter image description here

Objective C:

目标 C:

NSString * htmlString = @"<html><body> <b>  HTML in UILabel is here…. </b> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * yourLabel = [[UILabel alloc] init];
yourLabel.attributedText = attrStr;

Swift:

迅速:

var htmlString = “<html><body> <b>  HTML in UILabel is here…. </b> </body></html>”
var attrStr: NSAttributedString? = nil
do {
 if let data = htmlString.data(using: .unicode) {
 attrStr = try NSAttributedString(data: data, options: [
 NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html.rawValue
 ], documentAttributes: nil)
 }
} catch {
}
var yourLabel = UILabel()
yourLabel.attributedText = attrStr

Ref: https://medium.com/@javedmultani16/html-text-in-uilabel-ios-f1e0760bcac5

参考:https: //medium.com/@javedmultani16/html-text-in-uilabel-ios-f1e0760bcac5

回答by Venu Gopal Tewari

**// Swift 4 compatible | with setting of colour and font options:**

// add following extension to String:

        func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {

                let sizeInPx = (size * 0.75)

                do {
                  let htmlCSSString = "<style>" +
                    "html *" +
                    "{" +
                    "font-size: \(sizeInPx)pt !important;" +
                    "color: \(color.hexString ?? "#000000") !important;" +
                    "font-family: \(family ?? "SFUIText-Regular"), SFUIText !important;" +
                  "}</style> \(self)"

                  guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                    return nil
                  }

                  return try NSAttributedString(data: data,
                                                options: [.documentType: NSAttributedString.DocumentType.html,
                                                          .characterEncoding: String.Encoding.utf8.rawValue],
                                                documentAttributes: nil)
                } catch {
                  print("error: ", error)
                  return nil
                }
              }

        // add following extension to UIColor:

        extension UIColor{

          var hexString:String? {
            if let components = self.cgColor.components {
              let r = components[0]
              let g = components[1]
              let b = components[2]
              return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
            }
            return nil
          }
        }

    // Sample Use:

    yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
                                                                           size: yourLabel.font.pointSize,
                                                                           color: yourLabel.textColor)

回答by Chowdhury Md Rajib Sarwar

The above answer in Swift 3:

Swift 3 中的上述答案:

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }
    return html
}