Swift:在标签或文本视图中显示 HTML 数据

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

Swift: Display HTML data in a label or textView

htmliosswiftuitextviewnsattributedstring

提问by Talha Ahmad Khan

I have some HTML data, which contains headings, paragraphs , images and lists tags.

我有一些 HTML 数据,其中包含标题、段落、图像和列表标签。

Is there a way to display this data in one UITextViewor UILabel?

有没有办法在一个UITextView或一个中显示这些数据UILabel

回答by Roger Carvalho

For Swift 4:

对于 Swift 4:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

Then, whenever you want to put HTML text in a UITextView use:

然后,每当您想将 HTML 文本放入 UITextView 时,请使用:

textView.attributedText = htmlText.htmlToAttributedString

回答by garie

Here is a Swift 3 version:

这是一个 Swift 3 版本:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.

我在这里发现了一些其他答案的问题,我花了一些时间才把它弄对。我设置了换行模式和行数,以便在 HTML 跨越多行时标签大小合适。

回答by Himanshu

Add this extension to convert your html code to a regular string:

添加此扩展以将您的 html 代码转换为常规字符串:

    extension String {

        var html2AttributedString: NSAttributedString? {
            guard
                let data = dataUsingEncoding(NSUTF8StringEncoding)
            else { return nil }
            do {
                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
            } catch let error as NSError {
                print(error.localizedDescription)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
}

And then you show your String inside an UITextView Or UILabel

然后你在 UITextView 或 UILabel 中显示你的字符串

textView.text = yourString.html2Stringor

textView.text = yourString.html2String或者

label.text = yourString.html2String

回答by Kassy Barb

I had problems to change attributes of text after that, and I could see others asking why...

之后我在更改文本属性时遇到了问题,我可以看到其他人问为什么......

So best answer is to use extension with NSMutableAttributedString instead:

所以最好的答案是使用 NSMutableAttributedString 扩展:

extension String {

 var htmlToAttributedString: NSMutableAttributedString? {
    guard let data = data(using: .utf8) else { return nil }
    do {
        return try NSMutableAttributedString(data: data,
                                      options: [.documentType: NSMutableAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                      documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
 }

}

And then you can use it this way:

然后你可以这样使用它:

if let labelTextFormatted = text.htmlToAttributedString {
                let textAttributes = [
                    NSAttributedStringKey.foregroundColor: UIColor.white,
                    NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13)
                    ] as [NSAttributedStringKey: Any]
                labelTextFormatted.addAttributes(textAttributes, range: NSRange(location: 0, length: labelTextFormatted.length))
                self.contentText.attributedText = labelTextFormatted
            }

回答by Ved Rauniyar

Swift 3.0

斯威夫特 3.0

var attrStr = try! NSAttributedString(
        data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
label.attributedText = attrStr

回答by Nikolay Khramchenko

I'm using this:

我正在使用这个:

extension UILabel {
    func setHTML(html: String) {
        do {
            let attributedString: NSAttributedString = try NSAttributedString(data: html.data(using: .utf8)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
            self.attributedText = attributedString
        } catch {
            self.text = html
        }
    }
}

回答by Alex Morel

Swift 3

斯威夫特 3

extension String {


var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}

回答by Iyyappan Ravi

Try this:

尝试这个:

let label : UILable! = String.stringFromHTML("html String")

func stringFromHTML( string: String?) -> String
    {
        do{
            let str = try NSAttributedString(data:string!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true
                )!, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedLong: NSUTF8StringEncoding)], documentAttributes: nil)
            return str.string
        } catch
        {
            print("html error\n",error)
        }
        return ""
    }

Hope its helpful.

希望它有帮助。

回答by Ulysses

Display images and text paragraphs is not possible in a UITextViewor UILabel, to this, you must use a UIWebView.

不能在 aUITextView或 中显示图像和文本段落UILabel,为此,您必须使用UIWebView.

Just add the item in the storyboard, link to your code, and call it to load the URL.

只需在情节提要中添加项目,链接到您的代码,然后调用它来加载 URL。

OBJ-C

OBJ-C

NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];

Swift

迅速

let url = NSURL (string: "http://www.sourcefreeze.com");
let requestObj = NSURLRequest(URL: url!);
viewWeb.loadRequest(requestObj);

Step by step tutorial. http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

一步一步的教程。 http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

回答by Christopher Kevin Howell

If you want HTML, with images and a list, this isn't support by UILabel. However, I've found YYTextdoes the trick.

如果您想要带有图像和列表的 HTML,则 UILabel 不支持。但是,我发现YYText可以解决问题。