且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将NSAttributedString转换为HTML字符串?

更新时间:2023-02-03 10:13:40

使用设置为HTML( NSHTMLTextDocumentType)的文档类型属性( NSDocumentTypeDocumentAttribute )使用 dataFromRange:documentAttributes: ):

Use dataFromRange:documentAttributes: with the document type attribute (NSDocumentTypeDocumentAttribute) set to HTML (NSHTMLTextDocumentType):

NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};    
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];