2

我有我的自定义单元格“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()
    }
}
4

1 回答 1

3

正确的做法是prepareForReuse()在类中配置方法NewsCell

override func prepareForReuse() {
    super.prepareForReuse()

    imageView.image = //Default image
    //Whatever other things you need cleared.
}

每当 tableView 使单元格出列时,都会调用此方法。因此,任何缓存的数据都应在此处清除,否则它将保留在出队的单元格中,除非您在cellForRowAt方法中返回之前手动更改它。

于 2018-07-03T10:16:18.240 回答