Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法在swift中将NSAttributedString转换为HTML?_Html_Ios_String_Swift_Nsattributedstring - Fatal编程技术网

有没有办法在swift中将NSAttributedString转换为HTML?

有没有办法在swift中将NSAttributedString转换为HTML?,html,ios,string,swift,nsattributedstring,Html,Ios,String,Swift,Nsattributedstring,我想将NSAttributedString转换为HTML字符串。我一直在寻找如何解决这个问题,但还没有结果 知道我该怎么做吗 let attrStr = NSAttributedString(string: "Hello World") let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType] do { let htmlData = try attrStr.dataFromRang

我想将NSAttributedString转换为HTML字符串。我一直在寻找如何解决这个问题,但还没有结果

知道我该怎么做吗

let attrStr = NSAttributedString(string: "Hello World")
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
    let htmlData = try attrStr.dataFromRange(NSMakeRange(0, attrStr.length), documentAttributes:documentAttributes)
    if let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
        print(htmlString)
    }
}
catch {
    print("error creating HTML from Attributed String")
}

您可以使用此代码。它是一个swift示例,可以包装在自己的扩展名中,用于
nsattributestring

//swift 5.2
进口基金会
扩展NSAttribute字符串{
func toHtml()->字符串{
让documentAttributes=[NSAttributeString.DocumentAttributeKey.documentType:NSAttributeString.documentType.html]
做{
让htmlData=try self.data(from:NSMakeRange(0,self.length),documentAttribute:documentAttribute)
如果让htmlString=String(数据:htmlData,编码:String.encoding.utf8){
返回htmlString
}
}
抓住{
打印(“从属性字符串创建HTML时出错”)
}
归零
}
}

如果我只想要带有html标记的文本,则可能会出现重复。如何执行此操作?你有什么想法吗?我面临的最大问题是,当我使用它时,内容的字体越来越大,为什么我不知道,但它几乎翻了一番?这不会返回简单的html字符串。