[英]ReloadData with Protocol on custom cell with Collectionview?
我在這里嘗試了一堆答案,但是沒有運氣。
從Firebase提取數據后,我嘗試在自定義單元中重新加載我的collectionview。 我什至無法從自定義單元格中顯示打印語句。 不知道我在做什么錯。
在我的ViewController上,我有以下委托和調用,我做了一個按鈕來測試看是否在我的自定義單元格上出現了委托打印語句,但是沒有運氣。
protocol DiscoverControllerDelegate {
func didFetchData()
}
class DiscoverController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
let headerId = "headerId"
let database = FirebaseData.sharedInstance
var delegate: DiscoverControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Discover"
collectionView?.backgroundColor = .white
collectionView?.register(CategoriesCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(HeaderCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerId)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Refresh", style: .plain, target: self, action: #selector(reloadData))
database.retrieveData {
print("fetching data")
self.delegate?.didFetchData()
}
}
@objc func reloadData () {
print("attemping to reload")
self.delegate?.didFetchData()
}
*編輯以在我的自定義單元上添加我的覆蓋init:
class CategoriesCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, DiscoverControllerDelegate {
let itemCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .clear
return collectionView
}()
func didFetchData() {
print("RELOADING NOW!")
itemCollectionView.reloadData()
}
override init(frame: CGRect) {
super.init(frame: frame)
itemCollectionView.dataSource = self
itemCollectionView.delegate = self
itemCollectionView.register(ItemCell.self, forCellWithReuseIdentifier: cellId)
itemCollectionView.reloadData()
createLayout()
}
這里有很多錯誤。 原因是"RELOADING NOW!"
永不記錄日志是因為您從未在視圖控制器中設置委托。 如果您在DiscoverController
檢查self.delegate
,則可能為零。 但是,除非我誤解了您正在做什么,否則您現在的整個設置似乎都是有缺陷的。
您的用戶界面是什么樣的? 為什么CategoriesCell
具有UICollectionView
屬性? 它的itemCollectionView
屬性甚至沒有數據源或委托集,它不是@IBOutlet
但您正在對其調用reloadData()
。 不知道它什至顯示或您打算做什么。
我覺得這里可能有很多錯誤,而不僅僅是一件事情。 您可能想要瀏覽一些UITableView
和UICollectionView
教程,以了解iOS中的委托和數據源。
我不了解集合視圖,但是我將類似的協議結構與表視圖結合使用。 它們沒有太大的不同。 您的協議應該在單元類中,而不在控制器中。 在下面的文章中,我已經完成了用於表格視圖的步驟:
也許您可以根據需要對其進行調整...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.