如何在 UITextView 中动态加载图像
Posted
技术标签:
【中文标题】如何在 UITextView 中动态加载图像【英文标题】:How to load images dynamically inside UITextView 【发布时间】:2020-04-23 09:34:45 【问题描述】:我有一个 UITextView 并在其中附加了 TextAttachments。我正在从 web url 获取照片。代码如下:
image.load(url: URL(string: ("http://www.furkan.webofisin.com/upload/media/5db1b96366cd8.jpg")))
imageAttachment.image = image.image
let image1String = NSAttributedString(attachment: imageAttachment)
fullString.append(image1String)
这是作为扩展的加载函数:
var imageUrlString: String?
func load(urlString: String)
imageUrlString = urlString
guard let url = URL(string: urlString) else
DispatchQueue.main.async
let urlMessage = "Hata"
appDelegate.errorView(message: urlMessage, color: smoothGreenColor)
return
image = nil
if let imageFromCache = imageCache.object(forKey: urlString as NSString)
self.image = imageFromCache
return
URLSession.shared.dataTask(with: url) (data , response, error) in
if error != nil
DispatchQueue.main.async
let urlMessage = "Bir hata meydana geldi."
appDelegate.errorView(message: urlMessage, color: smoothGreenColor)
return
DispatchQueue.main.async
let imageToCache = UIImage(data: data!)
if self.imageUrlString == urlString
self.image = imageToCache
imageCache.setObject(imageToCache ?? UIImage(named: "astast")!, forKey: urlString as NSString)
.resume()
由于缓存,刷新页面后第一次不显示图像。 我检查了 image.image 作为 UIImage 但在加载完成之前它总是为零。
这是第一次打开的截图。
At first opening image data is nil
如何在图像数据填充后检测和重新加载图像。
【问题讨论】:
【参考方案1】:添加完成作为获取图像的调用最初是异步的,与本地缓存不同
func load(urlString: String,completion:@escaping(() -> () ))
imageUrlString = urlString
guard let url = URL(string: urlString) else
DispatchQueue.main.async
let urlMessage = "Hata"
appDelegate.errorView(message: urlMessage, color: smoothGreenColor)
return
image = nil
if let imageFromCache = imageCache.object(forKey: urlString as NSString)
self.image = imageFromCache
completion()
return
URLSession.shared.dataTask(with: url) (data , response, error) in
if error != nil
DispatchQueue.main.async
let urlMessage = "Bir hata meydana geldi."
appDelegate.errorView(message: urlMessage, color: smoothGreenColor)
return
DispatchQueue.main.async
let imageToCache = UIImage(data: data!)
if self.imageUrlString == urlString
self.image = imageToCache
imageCache.setObject(imageToCache ?? UIImage(named: "astast")!, forKey: urlString as NSString)
completion()
.resume()
打电话
image.load(url: URL(string: ("http://www.furkan.webofisin.com/upload/media/5db1b96366cd8.jpg")))
imageAttachment.image = image.image
let image1String = NSAttributedString(attachment: imageAttachment)
fullString.append(image1String)
【讨论】:
谢谢,但它不起作用。我在完成时调用此函数,第一次尝试未加载图像,但当我关闭并重新打开加载的控制器图像时 我的意思是,如果在第一次尝试获取图像之前缓存,否则显示 nil以上是关于如何在 UITextView 中动态加载图像的主要内容,如果未能解决你的问题,请参考以下文章
动态 UITableViewCell 高度内的动态 UITextView?
动态 UIScrollView 中的动态 UITextView - iOS