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

时间:2014-09-16 23:15:09

标签: html ios swift uiwebview uilabel

我想在IOS的UILabel上显示 html 格式的文字。

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

Set TextView text from html-formatted string resource in XML

我想知道ios中是否有相同的内容?

我搜索并找到这个帖子:

How to show HTML text from API on the iPhone?

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

那还有其他选择吗?

谢谢。

7 个答案:

答案 0 :(得分:50)

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

}

答案 1 :(得分:48)

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

答案 2 :(得分:21)

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

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

答案 3 :(得分:14)

Swift 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

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

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

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

答案 4 :(得分:0)

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.

答案 5 :(得分:0)

对我来说,保罗的回答很奏效。但是对于自定义字体,我不得不采取以下措施。

//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)
                }

            }
        }

答案 6 :(得分:0)

Objective-C版本:

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

这只是以上答案的Objective-C转换。上面的所有答案都是正确的,为此,从以上答案中获取参考