簡體   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