Html 如何在ios标签中显示html格式的文本

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

How to display html formatted text in ios label

htmliosswiftuiwebviewuilabel

提问by hap497

I would like to display htmlformatted text on a UILabelin IOS.

我想在 IOS 中显示html格式的文本UILabel

In Android, it has api like this .setText(Html.fromHtml(somestring));

在Android中,它有这样的api .setText(Html.fromHtml(somestring));

Set TextView text from html-formatted string resource in XML

从 XML 格式的 html 格式字符串资源设置 TextView 文本

I would like to know what / if there is an equivalent in ios?

我想知道什么/是否在 ios 中有等价物?

I search and find this thread:

我搜索并找到了这个线程:

How to show HTML text from API on the iPhone?

如何在 iPhone 上显示来自 API 的 HTML 文本?

But it suggests using UIWebView. I need to display html formatted string in each table cell, so I think have 1 webviewper row seems a bit heavy.

但它建议使用UIWebView. 我需要在每个表格单元格中显示 html 格式的字符串,所以我认为webview每行1个似乎有点重。

Is that any other alternative?

那还有其他选择吗?

Thank you.

谢谢你。

回答by ?ernando Valle

Swift 3.0

斯威夫特 3.0

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

}

回答by Daniele B

for Swift 2.0:

对于Swift 2.0

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

回答by Connor

You could try an attributed string:

您可以尝试使用属性字符串:

var attrStr = NSAttributedString(
        data: "<b><i>text</i></b>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil,
        error: nil)
label.attributedText = attrStr

回答by Paul B

Swift 4

斯威夫特 4

import UIKit
let htmlString = "<html><body> Some <b>html</b> string </body></html>"
// works even without <html><body> </body></html> tags, BTW 
let data = htmlString.data(using: String.Encoding.unicode)! // mind "!"
let attrStr = try? NSAttributedString( // do catch
    data: data,
    options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
    documentAttributes: nil)
// suppose we have an UILabel, but any element with NSAttributedString will do
label.attributedText = attrStr

Supplement: controlling the font of resulting formatted string

补充:控制生成的格式化字符串的字体

To use properly scaled (i.e. with respect to user settings) system (or any other) font you may do the following.

要使用适当缩放(即相对于用户设置)系统(或任何其他)字体,您可以执行以下操作。

let newFont = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: UIFont.systemFontSize)) // The same is possible for custom font.

let mattrStr = NSMutableAttributedString(attributedString: attrStr!)
mattrStr.beginEditing()
mattrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: mattrStr.length), options: .longestEffectiveRangeNotRequired) { (value, range, _) in
    if let oFont = value as? UIFont, let newFontDescriptor = oFont.fontDescriptor.withFamily(newFont.familyName).withSymbolicTraits(oFont.fontDescriptor.symbolicTraits) {
        let nFont = UIFont(descriptor: newFontDescriptor, size: newFont.pointSize)
        mattrStr.removeAttribute(.font, range: range)
        mattrStr.addAttribute(.font, value: nFont, range: range)
    }
}
mattrStr.endEditing()
label.attributedText = mattrStr

回答by Pranav Pravakar

For me, Paul's answer worked. But for custom fonts I had to put following hack.

对我来说,保罗的回答奏效了。但是对于自定义字体,我不得不进行以下 hack。

//Please take care of force unwrapping
let data = htmlString.data(using: String.Encoding.unicode)! 
        let mattrStr = try! NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil)
        let normalFont = UIFontMetrics.default.scaledFont(for: UIFont(name: "NormalFontName", size: 15.0)!)//
        let boldFont = UIFontMetrics.default.scaledFont(for: UIFont(name: "BoldFontName", size: 15.0)!)
        mattrStr.beginEditing()
        mattrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: mattrStr.length), options: .longestEffectiveRangeNotRequired) { (value, range, _) in
            if let oFont = value as? UIFont{
                mattrStr.removeAttribute(.font, range: range)
                if oFont.fontName.contains("Bold"){
                    mattrStr.addAttribute(.font, value: boldFont, range: range)
                }
                else{
                    mattrStr.addAttribute(.font, value: normalFont, range: range)
                }

            }
        }

回答by Er. Vihar

Objective-C Version:

Objective-C 版本:

   NSError *error = nil;
   NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:contentData
                                                    options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType}
                                                    documentAttributes:nil error:&error];

This is just the Objective-C conversion of the above answers. All the answers above are right and reference taken from the above answersfor this.

这只是上述答案的Objective-C转换。以上所有答案都是正确的,参考以上答案

回答by Ved Rauniyar

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.