我有一个丰富的文本编辑器,其中用户可以编辑字体,颜色等。该模型将此信息保存在内存中作为NSAttributedString的一个实例。当我想要存储此信息并写入磁盘时,我通过以下函数将属性字符串转换为html:
func attributedStringToHtml(attributedString: NSAttributedString) -> String {
var ret = ""
do {
let htmlData = try attributedString.data(from: NSRange( location: 0, length: attributedString.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.html])
ret = String.init(data: htmlData, encoding: String.Encoding.utf8)!
} catch { print("error:", error) }
return ret
}为了将数据从磁盘拉回到NSAttributedString的实例中,我使用:
func htmlToAttributedString(htmlString: String) -> NSAttributedString {
return NSAttributedString.init(html: htmlString.data(using: String.Encoding.utf8)!, documentAttributes: nil)!
}通过多次循环这些函数,问题就会出现,即:
保存->加载->保存->加载->保存->加载。
在每个加载周期之后,存储的颜色会变得越来越暗。我相信这与色彩空间的转换有关?
此行为在macOS 10.13上不会发生。将其复制并粘贴到操场中,作为正在发生的情况的示例:
import AppKit
import PlaygroundSupport
func htmlToAttributedString(htmlString: String) -> NSAttributedString {
return NSAttributedString.init(html: htmlString.data(using: String.Encoding.utf8)!, documentAttributes: nil)!
}
func attributedStringToHtml(attributedString: NSAttributedString) -> String {
var ret = ""
do {
let htmlData = try attributedString.data(from: NSRange( location: 0, length: attributedString.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.html])
ret = String.init(data: htmlData, encoding: String.Encoding.utf8)!
} catch {
print("error:", error)
}
return ret
}
let initialHtmlString = "<!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<meta name=\"CocoaVersion\" content=\"1671.5\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; line-height: 16.0px; font: 14.0px Helvetica; color: #FF0000; -webkit-text-stroke: #000000}\nspan.s1 {font-kerning: none}\n</style>\n</head>\n<body>\n<p class=\"p1\"><span class=\"s1\">Double-click to edit this text</span></p>\n</body>\n</html>\n"
var attributedString = htmlToAttributedString(htmlString: initialHtmlString)
var backToHtml = attributedStringToHtml(attributedString: attributedString)
var backToAttributedString = htmlToAttributedString(htmlString: backToHtml)
var backToHtmlAgain = attributedStringToHtml(attributedString: backToAttributedString)
print(backToHtmlAgain) // notice the html color value is now f6000b发布于 2019-07-19 08:58:15
我可以通过使用NSAttributedString.DocumentType.rtf代替html来解决这个问题。
https://stackoverflow.com/questions/57102956
复制相似问题