【问题标题】:Reusing cells in UITableView在 UITableView 中重用单元格
【发布时间】:2018-11-27 17:29:37
【问题描述】:

我有我的自定义单元格“NewsCell”。它包含我的自定义视图“ImageMosaicView”(这只是 UIView 的子类)。我用它来显示像 Facebook 帖子中的照片。我只是将图像的 url 传递给 ImageMosaicView 的实例,然后它会加载并显示。

我有一个问题。当我快速滚动 tableView 时,前一个单元格中的图像会在新单元格中出现片刻,同时正在加载新图像。但我不知道它们是如何出现在那里的,因为我提供了默认图像。 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()
    }
}

【问题讨论】:

    标签: ios swift uitableview prepareforreuse


    【解决方案1】:

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

    override func prepareForReuse() {
        super.prepareForReuse()
    
        imageView.image = //Default image
        //Whatever other things you need cleared.
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      相关资源
      最近更新 更多