Swift - 将html字符串转换为属性字符串并再次返回时,字体大小会增加

时间:2017-06-16 13:14:40

标签: ios swift uitextview nsattributedstring

我有一个textView,允许用户输入NSAttributedString,转换为html字符串,然后存储到数据库中。我还有代码将html字符串转换回来并在textView中显示以进行编辑。我的转换代码是

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        return html
    }
}

extension NSAttributedString {
    func htmlString() -> String? {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
            if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) { return htmlString }
        }
        catch {}
        return nil
    }
}

但问题是,每次保存和显示字符串时,所有字体大小都会增加。例如,我有一个html字符串

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 17.0px '.SF UI Text'; color: #000000}
span.s1 {font-family: '.SFUIText'; font-weight: normal; font-style: normal; font-size: 17.00pt}
</style>
</head>
<body>
<p class="p1"><span class="s1">text</span></p>
</body>
</html>

将其转换为NSAttributedString并再次返回后,其他所有内容都相同,但css行更改为此。

<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 28.0px; font: 22.7px '.SF UI Text'; color: #000000; -webkit-text-stroke: #000000}
span.s1 {font-family: '.SFUIText'; font-weight: normal; font-style: normal; font-size: 22.67pt; font-kerning: none}
</style>

我错过了什么吗?任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

尝试从一些帮助中找到的这种方法然后转换为Swift 3:

func newAttrSize(blockQuote: NSAttributedString) -> NSAttributedString
{
    let yourAttrStr = NSMutableAttributedString(attributedString: blockQuote)
    yourAttrStr.enumerateAttribute(.font, in: NSMakeRange(0, yourAttrStr.length), options: .init(rawValue: 0)) {
        (value, range, stop) in
        if let font = value as? UIFont {
            let resizedFont = font.withSize(font.pointSize * 0.75)
            yourAttrStr.addAttribute(.font, value: resizedFont, range: range)
        }
    }

    return yourAttrStr
}

答案 1 :(得分:0)

我遇到了同样的问题,简单的解决方案是您只转换为RTF格式而不是HTML。很好。