繁体   English   中英

如何基于Firestore数据在collectionView中显示行标题和节标题?

[英]How to display row and section titles in collectionView based on Firestore data?

我正在尝试将基于日期的tableView中的节中的项目分类为节标题。 我创建了两个数组,以便以后可以将它们合并为节和行,例如:

var tableViewModel = [TableViewModel]()
var items = [TableViewModel]()

var sectionTableViewModel = [Timestamp]()
var sectionItems = [Timestamp]()

这是我从Firestore加载数据的方式:

ref.addSnapshotListener { documentSnapshot, error in
      guard let data = documentSnapshot else {
          print("Error fetching document: \(error!)")
          return
      }

      let documents = data.documents
      for document in documents {
          let item = TableViewModel(json: document.data())
          let sectionItem: Timestamp = document.data()["date"] as! Timestamp

           self.items.append(item)
          if (!self.sectionItems.contains(sectionItem)) {
              self.sectionItems.append(sectionItem)
          }
      }

      // Display as descending order.
      self.tableViewModel = self.items as [TableViewModel]
      self.sectionTableViewModel = self.sectionItems as [Timestamp]

      self.collectionView.reloadData()
  }

现在,我无法确定如何将我的项目划分为tableView的各个部分。 到目前为止,我所做的是填充以下部分和行:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.tableViewModel.count
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return self.sectionTableViewModel.count
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "sectionHeader", for: indexPath) as! SectionHeaderCollectionReusableView

    header.headerLabel.text = sectionTableViewModel[indexPath.section]
        return header
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UpdatesCollectionViewCell

    cell.titleLabel.text =  self.tableViewModel[indexPath.row].title
}

它的作用是正确显示节标题,但每个节都一遍又一遍地显示所有数据,我无法确定如何根据日期过滤数据。 我创建另一个阵列和合并两个tableViewModelsectionTableViewModel togethher? 还是我过滤cellForItemAt的项目? 还是更改Firestore数据的结构?

您面临的问题是数据结构的问题。 您可以使用一系列日期来定义您的部分,这很好。 然后,您将获得一个定义行/项目的数组,这也很好,但是您需要的是每个日期/节都有一个行/项目的数组。

现在,您拥有的所有部分都使用相同的数组,这就是为什么重复项的原因。

现在,要解决此问题,您可以在前端或从Firestore的后端执行几项操作。

您可以在Firestore上创建数据结构,其中文档包含日期和数据数组。

您可以做的另一件事是使用当前数据结构为每个日期创建一个新数组。 要知道Dictionary属于哪个日期, Dictionary将完成这项工作。

现在,就我提供代码或直接为您提供解决方案而言,我不会这样做,因为那不是别人的学习方式。 如果您还有其他问题要澄清,我将很乐意回答!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM