我有我的自定义单元格“NewsCell”。它包含我的自定义视图“ImageMosaicView”(这只是 UIView 的子类)。我用它来显示像 Facebook 帖子中的照片。我只是将图像的网址传递给 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()
}
}