我在应用程序的主视图控制器上有一个带有UIButton的集合视图,当用户更改其状态时,都需要对其进行更改。
我使用的是Firebase观察者值,所以当值更改后,它将立即更改按钮的颜色和图像。
问题是,当我从第二个单元格向前更改值时,它将所有单元格都更改为。
为了更好的理解,我添加了图片:
This is the cells before changing the value of the second one.
And this is the what happens after I changed only the second cell values on firebase
如您所见,它也会影响第一个单元格。 该观察者的值使用事务块从另一个视图控制器更改。
我在Google上搜索了此问题,发现了类似的问题,但没有一个答案可以解决此问题。
这是集合视图的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "group_card_cell", for: indexPath) as! HomeGroupCollectionViewCell
cell.prepareForReuse()
cell.groupName.text = groups[indexPath.row].name
cell.groupSchedule.text = "\(groups[indexPath.row].day!), Around \(groups[indexPath.row].time!)"
cell.cardMoreButtonRef.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
cell.cardMoreButtonRef.tag = indexPath.row
//Changing card attending color and value:
self.ref.child("Groups").child(groups[indexPath.row].uid!).child("groupFriendsList").child(currentUser!.uid).observe(.value) { (snapshot) in
guard let value = snapshot.value as? String else {return}
switch value{
case "Going":
cell.groupAttendButtonRef.backgroundColor = UIColor.init(named: "GoingColor")
cell.groupAttendButtonRef.setImage(UIImage(named: "icons8-checkmark_filled"), for: .normal)
case "Not Going":
cell.groupAttendButtonRef.backgroundColor = UIColor.init(named: "NotGoingColor")
cell.groupAttendButtonRef.setImage(UIImage(named: "icons8-delete_sign_filled"), for: .normal)
case "Maybe":
cell.groupAttendButtonRef.backgroundColor = UIColor.init(named: "MaybeColor")
cell.groupAttendButtonRef.setImage(UIImage(named: "icons8-minus_math_filled"), for: .normal)
default:
cell.groupAttendButtonRef.backgroundColor = UIColor.init(named: "MaybeColor")
cell.groupAttendButtonRef.setImage(UIImage(named: "icons8-minus_math_filled"), for: .normal)
}
}
return cell
}
谢谢!
答案 0 :(得分:0)
您是否尝试过在Firebase事件回调中为特定indexPath检索cell
?
您可以使用-
let specificCell = collectionView.cellForItem(at: IndexPath(row: row, section: section))
以仅基于indexPath的单元格
或者您可以使用重用标识符获取它-
let idpath = IndexPath(row: indexPath.row-1, section: indexPath.section)
let specificCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: idpath)
一旦有了该单元格,就可以相应地设置该单元格的groupAttendButtonRef
。