在表格视图中滚动出现故障且速度缓慢
Posted
技术标签:
【中文标题】在表格视图中滚动出现故障且速度缓慢【英文标题】:Scrolling in table view is glitchy and slow 【发布时间】:2021-08-28 15:59:19 【问题描述】:我的表格视图单元格中有下面的代码,用于加载用户在主页提要上的帖子。我正在调整图像大小,以便更好地控制应用程序中显示的图像大小。代码工作正常,图像大小调整得很好。然而,这种调整大小的过程会显着减慢帖子提要的速度,并且现在滚动表格视图非常有问题。
有人知道如何以更有效的方式重写它吗?
func set(post:Posts)
self.post = post
// get PROFILE image
let url = post.url
profileImageView.sd_setImage(with: url, completed: nil)
// get MEDIA image
let mediaUrl = post.urlM
MediaPhoto.sd_setImage(with: mediaUrl, completed: nil)
if let imageData: NSData = NSData(contentsOf: mediaUrl)
let image = UIImage(data: imageData as Data)
let newWidth = MediaPhoto.frame.width
let scale = newWidth/image!.size.width
let newHeight = image!.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image!.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
MediaPhoto.image = newImage
【问题讨论】:
【参考方案1】:不建议在单元格中进行繁重的工作,例如渲染或格式化等。
我建议使用 kingfisher 下载图像并显示它们。
查看更多:Kingfisher
其中包含一些有用的功能,例如:
异步图片下载和缓存。 提供有用的图像处理器和过滤器(在这种情况下您需要) 还有很多其他功能...要调整图像大小,请按照以下代码:
let resizingProcessor = ResizingImageProcessor(referenceSize: CGSize(width: 100.0 , height: 100.0))
let url = URL(string: path)
imageView.kf.indicatorType = .activity
imageView.kf.setImage(with: url,
options: [.processor(resizingProcessor)],
completionHandler: nil
)
有关使用 kingfisher 调整大小的更多信息,请访问以下链接:
Kingfishe Cheat-Sheet
【讨论】:
【参考方案2】:你应该尝试使用NSCache
,我通常创建一个扩展文件并创建这个方法:
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView
func loadImageUsingCacheWithUrlString(_ urlString: String)
let strUniqueIdentifier_Initial = urlString
self.accessibilityLabel = strUniqueIdentifier_Initial
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage
self.image = cachedImage
return
guard let url = URL(string: urlString) else return
URLSession.shared.dataTask(with: url, completionHandler: (data, response, error) in
if error != nil
print(error ?? "")
return
let strUniqueIdentifier_Current = self.accessibilityLabel
if strUniqueIdentifier_Initial != strUniqueIdentifier_Current
return
DispatchQueue.main.async(execute:
if let downloadedImage = UIImage(data: data!)
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
self.image = downloadedImage
)
).resume()
然后像这样调用方法:
// I usually use optional values when creating custom objects
if let imgUrl = post?.url
imgView.loadImageUsingCacheWithUrlString(imgUrl)
我个人喜欢这个选项,因为我不喜欢使用额外的库。
【讨论】:
以上是关于在表格视图中滚动出现故障且速度缓慢的主要内容,如果未能解决你的问题,请参考以下文章