【问题标题】:Firebase observer value affect all collection view cellsFirebase 观察者值影响所有集合视图单元格
【发布时间】:2018-11-07 00:11:21
【问题描述】:

我在应用程序的主视图控制器上有一个带有 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

如您所见,它也会影响第一个单元格。 使用事务块从另一个视图控制器更改此观察者的值。

我在谷歌上搜索了这个问题,发现了类似的问题,但没有一个答案能解决这个问题。

这里是集合视图的代码:

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
}

提前致谢!

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    您是否尝试过在 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

    【讨论】:

      最近更新 更多