说明

当你要显示html到UILabel,UITextView的时候,需要把html字符串,转换为NSAttributedString.

最好情况下,加个String的extension。

extension String {public var convertHtmlToNSAttributedString: NSAttributedString? {guard let data = data(using: .utf8) else {return nil}do {return try NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)}catch {print(error.localizedDescription)return nil}}public func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? {guard let font = font else {return convertHtmlToNSAttributedString}let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)";guard let data = modifiedString.data(using: .utf8) else {return nil}do {return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)}catch {print(error)return nil}}
}

调用如下:

myUILabel.attributedText = "Swift is awesome!!!".convertHtmlToAttributedStringWithCSS(font: UIFont(name: "Arial", size: 16), csscolor: "black", lineheight: 5, csstextalign: "center")

乱码问题

如果只是运用上面代码,没有发现问题。因为string的编码,和NSAttributeString的编码是一样的。下面举个乱码的例子。

let htmlString = """<html><head><style type=\"text/css\">body { font-family: Mehr Nastaliq Web; font-size: 22pt; white-space: pre-wrap; text-align: right; lang: en; direction: RTL; -webkit-user-select: none; meta charset=\"UTF-8\" }</style> </head><body leftmargin=\"20\" topmargin=\"0\" rightmargin=\"20\"> hello world! Arabic.<br/> مُدّعا عَنقا ہے اپنے عالَمِ تقریر کا میری تقریر کا مفہوم چونکہ عنقا یعنی معدوم ہے اور معدوم </body></html>"""let attributedString = try? NSAttributedString(data:htmlString.data(using: String.Encoding.utf8)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)textView.attributedText = attributedString

显示效果如下:

如果把NSAttributedString的编码去掉以后,修改的变量attributedString如下。

let attributedString = try? NSAttributedString(data:htmlString.data(using: String.Encoding.utf8)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

就会显示乱码

如果同时修改字符串编码和NSAttributedString的编码为unicode, 结果也是正常的。读者可自行验证。

let attributedString = try? NSAttributedString(data:htmlString.data(using: String.Encoding.unicode)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding:String.Encoding.unicode.rawValue], documentAttributes: nil)

需要了解字符编码:请参考文章 > 关于字符编码,你所需要知道的(ASCII,Unicode,Utf-8,GB2312…)

代码下载

https://gist.github.com/zgpeace/24ee9264e83c984f00191091d7b632ae

参考

https://stackoverflow.com/questions/50363326/nsrangeexception-reason-nsbigmutablestring-characteratindex-index/61133696#61133696

https://johncodeos.com/how-to-display-html-in-uitextview-uilabel-with-custom-color-font-etc-in-ios-using-swift/

在UITextView显示HTML,以及NSAttributedString乱码问题解决 swift相关推荐

  1. Autovue显示dwg等图纸乱码问题解决

    一.问题描述: 在autovue预览cad文件时,发现原本cad中查看没有问题的东西,在autovue中显示如下,出现了字混乱,且有乱码之类的各种问题. 二.解决办法: 分析: 一般出现乱码问题,大部 ...

  2. 关于Proteus 8仿真STM32串口通信时显示数据错误或乱码问题解决!

    本人用Proteus 8仿真STM32F401RBT6串口通信时一直不能正确收发数据,写到板子通信数据显示正常,也在csdn查了很多人的解决办法,但都没了正常解决,直到看到某大神说到串口参数,我试着改 ...

  3. 网页查看js源码汉字显示乱码问题解决

    网页查看js源码汉字显示乱码问题解决 参考文章: (1)网页查看js源码汉字显示乱码问题解决 (2)https://www.cnblogs.com/JulyChen/p/5997980.html (3 ...

  4. python2.7下使用logging模块记录日志到终端显示乱码问题解决

    python2.7下使用logging模块记录日志到终端显示乱码问题解决 参考文章: (1)python2.7下使用logging模块记录日志到终端显示乱码问题解决 (2)https://www.cn ...

  5. QT的中文显示乱码问题解决

    QT的中文显示乱码问题解决 QT的中文显示乱码问题解决: 1.查看源文件的编码格式,有必要的话转换源文件的编码格式再重新编译运行尝试汉字能否正常显示. 2.在代码里面解决: 3.用法: QT的中文显示 ...

  6. powerShell 使用 chcp 65001 之后,还是显示乱码问题解决

    ■问题描述 使用cmd 的 type 命令 显示文件内容 最开始时乱码,(默认MS 936) chcp 65001  切换成 UTF-8 之后,就可以正常显示了. 但是,powershell中,即使, ...

  7. python json.loads json.dumps(ensure_ascii = False) 汉字乱码问题解决

    python json.loads json.dumps(ensure_ascii = False) 汉字乱码问题解决 python 转换为json时候 汉字编码问题 2017年03月23日 18:5 ...

  8. html2image乱码问题,HtmlImageGenerator字体乱码问题解决、html2image放linux上乱码问题解决...

    使用html2image-0.9.jar生成图片. 在本地window系统正常,放到服务器linux系统时候中文乱码问题.英文可以,中文乱码应该就是字体问题了. 一.首先需要在linux安装字体,si ...

  9. Python字符串的encode与decode研究心得乱码问题解决方法

    Python字符串的encode与decode研究心得乱码问题解决方法 为什么Python使用过程中会出现各式各样的乱码问题,明明是中文字符却显示成"\xe4\xb8\xad\xe6\x96 ...

  10. QT学习笔记(四):Qt5+MSVC编译 中文字符显示乱码问题解决

    QT学习笔记(四):Qt5+MSVC编译 中文字符显示乱码问题解决 问题: 1.解决方法一: 2.解决方法二: 3.解决方法三: 4.解决方法四: 结果显示: Qt5+MSVC编译 中文字符显示乱码. ...

最新文章

  1. .NET Core微服务之路:不断更新中的目录 (v0.42)
  2. python读取字典元素笔记_Python中列表、字典、元组数据结构的简单学习笔记
  3. jvm内存溢出分析实践案例:javax.crypto.JceSecurity大量BouncyCastleProvider实例无法被回收
  4. Yii的gii-modules
  5. CentOS 6.7 配置JSP运行环境之tomcat
  6. mysql避免死锁的方法
  7. 苹果证实将弃用Windows版QuickTime
  8. MATLAB 读取txt文件(importdata函数)
  9. (1.2.4)无法将类型“NPOI.SS.UserModel.Sheet”隐式转换为“NPOI.HSSF.UserModel.HSSFSheet”。...
  10. 鼠标的默认事件之oncontextmenu及其案例
  11. 李宏毅机器学习——逻辑回归
  12. 2022年认证杯SPSSPRO杯数学建模A题(第一阶段)人员的紧急疏散求解全过程文档及程序
  13. 记一次系统蓝屏处理IRQL_NOT_LESS_OR_EQUAL
  14. html平板电脑打不开,平板电脑浏览器打不开网页
  15. Windows-EFS加密文件
  16. [爱情智慧]爱作的女人,最后都不怎么好!学会述情才能婚姻幸福!
  17. html5怎么写副标题,毕业论文副标题怎么写
  18. CorelDRAW 2022中文精简64位直装版下载
  19. 为何excel中数据无法计算机,造成Excel表格打不开的几种原因及解决办法
  20. C#实现监控网络流量

热门文章

  1. zabbix内网安装部署_搭建环境tomcat+nginx+keepalived+zabbix
  2. convert oracle 字符串_oracle的concat、convert、listagg函数(字符串拼接和类型转换)...
  3. React Component里的状态机Pattern
  4. sqool导出oracle数据
  5. 输入框正则表达式大全
  6. MySQL的Grant命令[转]
  7. 数据仓库专题(14)-数据仓库建设指导原则:一切以就绪数据为主
  8. .Top域名:新顶级域名还原互联网安全发展
  9. C#常用操作类库一(验证类)
  10. js 对象深拷贝_javascript深拷贝与浅拷贝