首页 > 解决方案 > 从 HTML 转换为 NSAttributedString 错误的属性

问题描述

我正在尝试将 a 保存NSAttributedString到服务器,当我需要它时,将其与所有属性一起取回

经过一个小时的搜索,我找到了这段代码

extension NSAttributedString {
var toHTML: String {
    let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
    do {
        let htmlData = try self.data(from: NSRange(location: 0, length: self.length), documentAttributes:documentAttributes)
        if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
            return htmlString
        }
    }
    catch {
        print("error creating HTML from Attributed String")
        return ""
    }
    return ""
}

extension String {
var fromHTML: NSAttributedString {
    guard let data = data(using: .utf8) else { return NSAttributedString() }
    do {
        return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch {
        return NSAttributedString()
    }
}

当我需要将 a 转换NSAttributedString为 HTML 格式时,它做得对

"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n<title></title>\n<meta name=\"Generator\" content=\"Cocoa HTML Writer\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Palatino}\nspan.s1 {font-family: \'Palatino\'; font-weight: bold; font-style: normal; font-size: 20.00pt}\n</style>\n</head>\n<body>\n<p class=\"p1\"><span class=\"s1\">Hello world</span></p>\n</body>\n</html>\n"

但是当我尝试将其格式化回时NSAttributedString,它会更改字体的实际大小

Hello world{
NSColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSFont = "<UICTFont: 0x121d04440> font-family: \"Palatino\"; font-weight: bold; font-style: normal; font-size: 26.67pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 31/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSStrokeWidth = 0;
}

我在这里做错了什么?

标签: htmlswiftnsattributedstring

解决方案


推荐阅读