首先,我想说这似乎是SO上的常见问题,我已经阅读了从Swift到Obj-C的所有文章。在过去的9个小时里,我尝试了一堆不同的方法,但是我的问题仍然存在。
我有一个带有collectionView的vc(vc1)。在collectionView内,我有一个带有标签和其中的imageView的自定义单元格。在cellForItem内部,我还有一个属性也位于自定义单元格中,并且当从datasource[indePath.item]
设置该属性时,在该单元格内有一个属性观察器,该属性观察器为label和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 = ""
的所有位置添加了1个断点(总共3个),一旦collectionView重新加载,断点总是被命中6次(数据源中2个对象的3次)。prepareForReuse
中的第一次是第二次cellForItem
中的时间,cleanUpElements()
中的第三时间 最佳答案
原来,我不得不重置单元内的属性。即使单元已被重用并且priceLabel.text被清除,该属性仍保持其旧的bool
值。通过cellForItem重置它后,问题就消失了。
十个小时
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
}
关于ios - UICollectionViewCell中标签中的数据有时刷新时会刷新,而其他时候却不刷新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53982323/