HTML para NSAttributedString e NSAttributedString para HTML

Eu tenho um problema com NSAttributedString ...

Eu quero converter umString HTML em um NSAttributedString e trabalhe no NSAttributedString (altere algumas cores, tamanho da fonte, família da fonte, plano de fundo, cor do primeiro plano)e, em seguida, converta o texto HTML sem formatação do NSAttributedString.

Convertendonão é um problema, mas sempre que eu converter HTML para NSAS e voltar otamanho da fonte cada vez maior ?!

Aqui está uma foto e o código fonte do meu playground.

// Playground - noun: a place where people can play
// NSAS: - NSAttributedString

import UIKit

class Wrapper {

    //MARK: fields
    let apiHtml = "<div style='font-size: 18px'><span style='font-family:&#039;andale mono&#039;, times;'>Dies</span> <span style='font-family:&#039;comic sans ms&#039;, sans-serif;'>ist</span> <strong><span style='font-family:&#039;andale mono&#039;, sans-serif;';>eine</span></strong> <em>formatierte</em> <span style='text-decoration:underline;'>Karte</span>&#160;<span style='font-size:16px;'>die</span> <span style='background-color:#ffff00;'>es</span> zu &#220;bernehmen gilt</div>"

    var newGeneratedHtml = ""
    var textView : UITextView!

    //MARK: constructor
    init() {
        //init textview
        textView = UITextView(frame: CGRectMake(0, 0, 500, 300))

        //convert html into NSAS and set it to textview
        if let attributedText = getAttributedTextFromApiHtmlString(apiHtml) {
            textView.attributedText = attributedText
        }

        //get html text from textfields NSAS
        if let htmlText = getHtmlTextFromTextView() {
            newGeneratedHtml = htmlText
            println(htmlText)
        }

        //set the converted html from textfields NSAS
        if let attributedText = getAttributedTextFromApiHtmlString(newGeneratedHtml) {
            textView.attributedText = attributedText
        }

        //get html text from textfields NSAS
        if let htmlText = getHtmlTextFromTextView() {
            newGeneratedHtml = htmlText
            println(htmlText)
        }
    }

    //MARK: methods
    func getAttributedTextFromApiHtmlString(text : String) -> NSAttributedString? {
        if let attributedText = NSAttributedString(data: text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil, error: nil) {
            return attributedText
        }
        return nil
    }

    func getHtmlTextFromTextView() -> String? {
        let attributedTextFromTextView = textView.attributedText
        if let htmlData = attributedTextFromTextView.dataFromRange(NSMakeRange(0, attributedTextFromTextView.length), documentAttributes: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], error: nil) {
            if let htmlString = NSString(data: htmlData, encoding: NSUTF8StringEncoding) {
                return htmlString
            }
        }
        return nil
    }
}

var w = Wrapper()

Aqui está o resultado do playground, você pode ver que o segundo texto é maior que o primeiro, mas não mudei o tamanho da fonte em nenhum lugar.

Isso é um bug ou tive que definir um tamanho de fonte fixo?

Mas definir um tamanho de fonte fixo não é o que eu realmente quero, pois pode ser diferente para cada caractere ...

ATUALIZAR:

Aceito a resposta de @Lou Franco porque ele está certo. Não sei por que ele é convertidopx parapt e de volta, mas aqui está minha solução alternativa:

func getAttributedTextFromApiHtmlString(text : String) -> NSAttributedString? {
        if let attributedText = NSAttributedString(data: text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil, error: nil) {

            var res : NSMutableAttributedString = attributedText.mutableCopy() as NSMutableAttributedString
            res.beginEditing()
            var found : Bool = false;
            res.enumerateAttribute(NSFontAttributeName, inRange:NSMakeRange(0, res.length) ,options:NSAttributedStringEnumerationOptions.allZeros, usingBlock: {(value:AnyObject!, range:NSRange, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
                if ((value) != nil) {
                    let oldFont = value as UIFont;
                    let newFont = oldFont.fontWithSize(15)
                    res.removeAttribute(NSFontAttributeName, range:range)
                    res.addAttribute(NSFontAttributeName, value: newFont, range: range)
                    found = true
                    }
                })
            if !found {
                // No font was found - do something else?
            }
            res.endEditing()
            return res
        }
        return nil
    }

A única desvantagem disso é que vocêperder Text-Heights diferentes em sua AttributedString ....

Agora eu tenho que encontrar uma maneira de manter as diferentes alturas de texto ... Se alguém tiver a solução ou melhor solução, fique à vontade para postar sua resposta.

questionAnswers(3)

yourAnswerToTheQuestion