我有我的自定义单元“NewsCell”。它包含我的自定义视图“ImageMosaicView”(它只是 UIView 的子类)。我用它来显示照片,就像 Facebook 上发布的照片一样。我只是将图像的 url 传递给 ImageMosaicView 的实例,它会加载并显示它。
我有一个问题。当我快速滚动 tableView 时,上一个单元格中的图像会在新单元格中出现一段时间,同时加载新图像。但我不知道它们是如何出现在那里的,因为我提供了默认图像。这是一个例子
我怎样才能避免这种情况?
// 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()
}
}
执行此操作的正确方法是配置prepareForReuse()
里面的方法NewsCell
class.
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = //Default image
//Whatever other things you need cleared.
}
每当 tableView 将单元格出列时,就会调用此方法。因此,任何缓存的数据都应在此处清除,否则它将保留在出队单元中,除非您在将其返回到队列中之前手动更改它cellForRowAt
method.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)