【问题标题】:Display Images Between Text retrieved from server [SWIFT]在从服务器检索的文本之间显示图像 [SWIFT]
【发布时间】:2019-12-12 07:37:21
【问题描述】:

我想使用 NSTextAttachment 在文本之间显示图像,其中文本和图像都是从服务器检索的。我已经托管了要显示的文本的示例 JSON。在要显示的图像的文本和链接之间,需要显示图像的位置用“[IMAGE]”标记,在 JSON 中也是可用的。

for para in newsText{
    if(para == "[IMAGE]")
    {
        print("Image Found")
        let paraImageLink = images[self.imageCount]["link"] as? String


        let downloader = ImageDownloader.default
        downloader.downloadImage(with: URL(string:paraImageLink!)!, options: .none) { result in
            switch result {
            case .success(let value): let paraImageResized = self.ResizeImage(value.image, targetSize: CGSize(width: 500.0, height: 300.0))
            let imageAttachement = NSTextAttachment()
            imageAttachement.image = paraImageResized
            let imageString = NSAttributedString(attachment: imageAttachement)
            self.content.append(imageString)
            self.content.append(NSMutableAttributedString(string: "\n\n"))
            self.imageCount+=1

            case .failure(let error):
                print(error)
            }
        }
        //
    }
    else{
        self.content.append(NSAttributedString(string: para+"\n\n"))


    }


我面临的问题是图像根本没有显示。

完整的代码和示例项目位于: https://github.com/dnawarrior/textAttachment

用于检索数据的 JSON 托管在: https://www.npoint.io/docs/5ab45880fc3dd8c41671

【问题讨论】:

  • 是否有必要使用NSTextAttachment。为什么?你能用其他乐器吗?
  • 首先,如果您创建一个简单的项目并将有问题的代码放入其中,人们可以对其进行修改和更新代码,这将对您有更多帮助。其次,您最好先下载图像,然后使用它们创建属性字符串。最后,对于只是从互联网上下载一些资产,不要使用第三方库,自己做助手,它可以让你的最终应用程序更小,运行更快。
  • 我已经添加了项目..

标签: ios swift image nstextattachment


【解决方案1】:

你可以这样做,在图像下降后

DispatchQueue.main.async {
   self.text.attributedText = self.content
}

我认为这是一张网络图片。

 let imageURL : URL = URL(string: url)!

开发人员很少直接从url 获取图像。是同步的,挂起主线程。

我们一般用URLSession下载,在后台线程解码,然后在主线程渲染。

KingFisher 是一个不错的选择。


let downloader = ImageDownloader.default
downloader.downloadImage(with: url) { result in
    switch result {
    case .success(let value):
        print(value.image)
    case .failure(let error):
        print(error)
    }
}

来自Kingfisher Downloader

【讨论】:

  • 我试过了,但它仍然不会显示文本之间的图像。我正在尝试做的是在文本之间显示图像。即使图像正在加载,我也想在文本之间异步附加图像。
  • 我也是,加载时可以显示图片,注意:ONLY IN TABLEVIEW CELL
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多