问题描述
我有一个自定义单元格"NewsCell".它包含我的自定义视图"ImageMosaicView"(这只是UIView的子类).我用它来显示照片,就像在Facebook上发帖一样.我只是将图像的URL传递到ImageMosaicView的实例,然后将其加载并显示.
I have my custom cell 'NewsCell'. It contains my custom view 'ImageMosaicView' (that is just subclass of UIView). I use it to show photos like in post in Facebook. I just pass images' urls to ImageMosaicView's instance, and it loads it and shows.
我有一个问题.当我快速滚动tableView时,来自上一个单元格的图像会在新图像加载期间暂时出现在新单元格中.但是我不知道它们如何出现,因为我提供了默认图像.这里是一个例子
I have an issue. When I scroll my tableView fast, then images from previous cell appear in new cell for a moment, while new images are loading. But I have no idea how they appear there, because I provided default images. Here is an example
如何避免这种情况?
// ImageMosaicView.swift
class ImageMosaicView: UIView {
@IBOutlet var imageViews: [UIImageView]!
var urlStrings: [String] = [] {
didSet {
for imageView in imageViews {
if let url = URL(string: urlStrings[i]) {
imageView.loadImage(url: url)
}
}
}
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let _ = loadViewFromNib()
}
// MARK: - Methods
func loadViewFromNib() -> UIView {
let bundle = Bundle.init(for: type(of: self))
let nib = UINib(nibName: "ImageMosaicView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [
UIViewAutoresizing.flexibleWidth,
UIViewAutoresizing.flexibleHeight
]
addSubview(view)
return view
}
}
// How I provide urls for images:
// NewsViewController.swift. 'tableView(cellForRow:, indexPath:)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let news = newsCollection[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "NewsCell", for: indexPath) as! NewsCell
//...
cell.imageMosaicView.urlStrings = news.imageUrlsCollection
//...
return cell
} else {
return UITableViewCell()
}
}
推荐答案
执行此操作的正确方法是在 NewsCell
类中配置 prepareForReuse()
方法.
The right way to do this is to configure the prepareForReuse()
method inside the NewsCell
class.
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = //Default image
//Whatever other things you need cleared.
}
每当tableView使单元出队时,都会调用此方法.因此,除非在 cellForRowAt
方法中将其返回之前手动更改数据,否则应在此处清除所有缓存的数据,否则这些数据将保留在出队的单元格中.
This method is called whenever a tableView dequeues a cell. So any cached data should be cleared here or it will persist in the dequeued cell unless you manually change it before returning it in the cellForRowAt
method.
这篇关于重用UITableView中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!