How to display html formatted text in ios label

前端 未结 7 1375
逝去的感伤
逝去的感伤 2020-12-24 00:55

I would like to display html formatted text on a UILabel in IOS.

In Android, it has api like this .setText(Html.fromHtml(somestri

相关标签:
7条回答
  • 2020-12-24 01:29

    for 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
    
    0 讨论(0)
  • 2020-12-24 01:32

    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
    

    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
    
    0 讨论(0)
  • 2020-12-24 01:39

    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 {
    
    }
    
    0 讨论(0)
  • 2020-12-24 01:42

    Objective-C Version:

       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 answers for this.

    0 讨论(0)
  • 2020-12-24 01:43

    For me, Paul's answer worked. But for custom fonts I had to put following 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)
                    }
    
                }
            }
    
    0 讨论(0)
  • 2020-12-24 01:48
    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.
    
    0 讨论(0)
提交回复
热议问题