问题描述
在资产文件夹中,我有en
文件夹,这里有一些图片,例如其中一张-B12.png
。我不明白如何在标签中显示此本地图片。我有这样的代码:
let imageData:Data = (UIImage.init(named: "en/B12.png")!).pngData()!
let base64String = imageData.base64EncodedString()
let htmlString = """
<html><body><img src="data:image/png;base64,\(base64String)" /> width=\"360\" height=\"240\"></body></html>
"""
cell.questionText.attributedText = htmlString.convertToAttributedFromHTML()
但是当我运行这段代码时,我的标签上什么都没有看到。为什么会发生,如何解决这个问题?
解决方法
如果图像存储在应用程序的捆绑包中,则只需插入图像的URL
if let imagePath = Bundle.main.path(forResource: "B12",ofType: "png") {
let htmlString = """
<html><body><img src="\(imagePath)" /> width=\"360\" height=\"240\"></body></html>
"""
cell.questionText.attributedText = htmlString.convertToAttributedFromHTML()
}