I'm trying to use the current CollectionViewcell's IndexPath to access data from a dictionary. The dictionary's keys are of type Int. This CollectionView has "full page" cells, meaning that each cell takes up the full view area where I am using horizontal scrolling (paging enabled) to navigate between cells.
The dictionary is :
var dataFromServer: [Int: [VillageFestival]]?
Each CollectionViewCell has a TableView inside it, where I plan to have a variable number of rows, depending on how many items there are in [VillageFestival]
However, in CollectionView cellForItemAt indexPath
the behaviour of the method is causing some trouble, as printing indexPath.item or setting it as my navigationController's title, returns odd but "understandable" results given how I think dequeueReusableCell works?...
Example: the current index is 0. When I scroll to the right, the current index is now 2. If I navigate to page 6 and then one page back, the current index indicates 3.
I have changed my dictionary keys from Date to String and now to Int, in an attempt to simplify logic.. But the problem persists.
I am using a global pageIndex: Int
that is being updated inside CollectionView cellForItemAt
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
pageIndex = indexPath.item
self.navigationController?.navigationBar.topItem?.title = String(pageIndex)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
// CollectionViewCell resize to CollectionView Bounds
cell.tableViewCellOffsets = (UIApplication.shared.statusBarFrame.size.height + (self.navigationController?.navigationBar.frame.height ?? 0.0) , self.tabBarController?.tabBar.frame.height ?? 0)
return cell
}
In Tableview numberOfRowsInSection, I'm using pageIndex to access the dictionary values.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let festivals = dataFromServer?[pageIndex] else {return 0}
return festivals.count
}
With my current code, the app displays 0 rows for some pages and 1 row for others. My guess is that the collectionView's cellForItemAt is called before (also possibly after?) the tableView's methods and this makes using a global pageIndex unreliable...
Thanks!