来自CollectionViewCell中标签的数据有时刷新时会刷新,而其他时候却不刷新

时间:2018-12-30 23:38:56

标签: ios swift uicollectionview uilabel uicollectionviewcell

首先,我想说这似乎是SO上的常见问题,我已经阅读了从Swift到Obj-C的所有文章。在过去的9个小时里,我尝试了很多其他方法,但是我的问题仍然存在。

我有一个带有collectionView的vc(vc1)。在collectionView内,我有一个带有标签和其中的imageView的自定义单元格。在cellForItem内,我还有一个属性也位于自定义单元格内,当从datasource[indePath.item]设置属性时,该单元格内有一个属性观察器,可为标签和imageView设置数据。

vc1中有一个按钮可以按下vc2,如果用户从vc2中选择了某些内容,它将通过委托传递回vc1。 vc2弹出。

总是将正确的数据传回(我在调试器中检查了多次)。

问题是如果vc1中已有一个单元格,则在将新数据添加到数据源时,在我重新加载collectionView之后,来自第一个单元格的标签数据现在显示在新单元格中的标签上,并且该数据现在,新单元格中的内容显示在旧单元格的标签上。

我已经尝试了从prepareToReuse到删除标签的所有操作,但是由于某些原因,只有单元格的标签数据变得混乱。奇怪的是,有时标签正确更新而其他时候没有 imageView总是显示正确的图像,即使标签数据不正确,我也没有任何问题。数据源中的2个模型对象始终在正确的索引位置,并带有正确的信息。

可能是什么问题?

vc1: UIViewController, CollectionViewDataSource & Delegate {

    var datasource = [MyModel]() // has 1 item in it from viewDidLoad

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCell, for: indexPath) as! CustomCell

        cell.priceLabel.text = ""
        cell.cleanUpElements()
        cell.myModel = dataSource[indexPath.item]

        return cell
    }

    // delegate method from vc2
    func appendNewDataFromVC2(myModel: MyModel) {

        // show spinner

        datasource.append(myModel) // now has 2 items in it

        // now that new data is added I have to make a dip to fb for some additional information
        firebaseRef.observeSingleEvent(of: .value, with: { (snapshot) in

            if let dict = snapshot.value as? [String: Any] else { }

            for myModel in self.datasource {
                myModel.someValue = dict["someValue"] as? String
            }

            // I added the gcd timer just to give the loop time to finish just to see if it made a difference
            DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {

               self.datasource.sort { return $0.postDate > $1.postDate } // Even though this sorts correctly I also tried commenting this out but no difference
               self.collectionView.reloadData()

               // I also tried to update the layout
               self.collectionView.layoutIfNeeded()

               // remove spinner
            }
        })
    }    
}

下面的CustomCell。这是 myModel 属性观察器内部内容的简化版本。标签中显示的数据取决于其他数据,并且有一些条件可以确定它。将所有这些添加到cellForItem内将创建一堆代码,这就是为什么我不在那里更新数据(或在此处添加数据)并选择在单元内进行处理的原因。但是正如我之前所说,当我检查数据时,它始终是100%正确的。属性观察器始终可以正常工作。

CustomCell: UICollectionViewCell {

    let imageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()

    let priceLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    var someBoolProperty = false

    var myModel: MyModel? {
        didSet {

           someBoolProperty = true

           // I read an answer that said try to update the label on the main thread but no difference. I tried with and without the DispatchQueue
           DispatchQueue.main.async { [weak self] in
                self?.priceLabel.text = myModel.price!
                self?.priceLabel.layoutIfNeeded()  // tried with and without this
           }

           let url = URL(string: myModel.urlStr!)
           imageView.sd_setImage(with: url!, placeholderImage: UIImage(named: "placeholder"))

           // set imageView and priceLabel anchors
           addSubview(imageView)
           addSubview(priceLabel)

           self.layoutIfNeeded() // tried with and without this
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()

        // even though Apple recommends not to clean up ui elements in here, I still tried it to no success
        priceLabel.text = ""
        priceLabel.layoutIfNeeded() // tried with and without this
        self.layoutIfNeeded() // tried with and without this

        // I also tried removing the label with and without the 3 lines above 
        for view in self.subviews {
            if view.isKind(of: UILabel.self) {
                view.removeFromSuperview()
            }
        }
    }

    func cleanUpElements() {
        priceLabel.text = ""
        imageView.image = nil
    }
}

我为添加priceLabel.text = ""的每个地方添加了一个断点(共3个),并且collectionView重新加载后,断点总是被命中6次(对于数据源中的2个对象,则是3次)。 {1}},prepareForReuse中的第二次和cellForItem

中的第三次

1 个答案:

答案 0 :(得分:0)

结果是我不得不重置单元格内的属性。即使单元已被重用并且priceLabel.text被清除,该属性仍保持其旧的bool值。通过cellForItem重置后,问题就消失了。

10小时,smh

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCell, for: indexPath) as! CustomCell

    cell.someBoolProperty = false
    cell.priceLabel.text = ""
    cell.cleanUpElements()
    cell.myModel = dataSource[indexPath.item]

    return cell
}