I am trying to implement a collection view inside each table view cell in a table view, but am having trouble getting the collection view to reload at the right time. It looks like the collection view reloads itself after all the table view cells have been loaded, not each time a new cell is dequeued to the table view as I'm trying to make it do.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("LWTableViewCell") as! LWTableViewCell
cell.collectionView.delegate = self
cell.collectionView.dataSource = self
if dataIsReady == 1 {
setIndex = indexPath.row
print("in table view cellForRowAtIndexPath, setting setIndex at \(setIndex)")
cell.collectionView.reloadData()
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if dataIsReady == 1 {
print("In collection view numberOfItemsInSection setIndex is \(setIndex)")
return self.model.sets[setIndex].subsets!.count
}
else { return 0 }
}
In terminal, I get the following:
in table view cellForRowAtIndexPath, setting setIndex at 0
in table view cellForRowAtIndexPath, setting setIndex at 1
in table view cellForRowAtIndexPath, setting setIndex at 2
In collection view numberOfItemsInSection setIndex is 2
In collection view numberOfItemsInSection setIndex is 2
In collection view numberOfItemsInSection setIndex is 2
whereas I would expect to see the following order of events (given that the collection view reload method is/should be called each time a new table view cell is dequeued).
in table view cellForRowAtIndexPath, setting setIndex at 0
In collection view numberOfItemsInSection setIndex is 0
in table view cellForRowAtIndexPath, setting setIndex at 1
In collection view numberOfItemsInSection setIndex is 1
in table view cellForRowAtIndexPath, setting setIndex at 2
In collection view numberOfItemsInSection setIndex is 2
Any suggestions on why this behavior is happening, and how to potentially fix it would be much appreciated!
I have looked through some other questions on the topic, and am aware there are some tutorials on the topic (e.g., https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/), but before starting to do things with a different approach, I'd like to understand why the above doesn't seem to work / what could be done to make it work.