我试图在一个表视图中的每个表视图单元内实现一个集合视图,但是在让集合视图在正确的时间重新加载时遇到了麻烦。看起来收集视图在所有表视图单元格都加载后会重新加载,而不是每次尝试将新单元格从表视图中出队时都重新加载。
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 }
}
在终端中,我得到以下信息:
在表视图cellForRowAtIndexPath中,将setIndex设置为0
在表视图cellForRowAtIndexPath中,将setIndex设置为1
在表视图cellForRowAtIndexPath中,将setIndex设置为2
在集合视图中,numberOfItemsInSection setIndex为2
在集合视图中,numberOfItemsInSection setIndex为2
在集合视图中,numberOfItemsInSection setIndex为2
而我希望看到事件的顺序如下(假设每次将新的表格视图单元出队时,都应该调用collection view reload方法)。
在表视图cellForRowAtIndexPath中,将setIndex设置为0
在集合视图中,numberOfItemsInSection setIndex为0
在表视图cellForRowAtIndexPath中,将setIndex设置为1
在集合视图中,numberOfItemsInSection setIndex为1
在表视图cellForRowAtIndexPath中,将setIndex设置为2
在集合视图中,numberOfItemsInSection setIndex为2
对于为什么会出现此行为以及如何解决此问题的任何建议,将不胜感激!
我已经浏览了有关该主题的其他一些问题,并且知道有关该主题的一些教程(例如,https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/),但在开始用其他方法做事之前,我想了解为什么上述方法似乎行不通/可以做些什么。
您不能依赖调用顺序。当前,您正在尝试setIndex
从表视图的cellForRowAtIndexPath
方法传递到集合视图的委托方法。解决此问题的一种简单方法是,不使用单个变量传递行号,而是在集合视图的tag属性中传递行号。然后,每个集合视图将知道其相关的行号。IE
在表格视图中cellForRowAtIndexPath
:
cell.collectionView.tag = indexPath.row
然后在集合视图中numberOfItemsInSection
:
return self.model.sets[collectionView.tag].subsets!.count
还请注意,您无需dataIsReady
在这些方法中进行测试。仅在表格视图的中需要此代码tableView:numberOfRowsInSection:
。当数据未准备好时,它应该返回0(即没有要显示的行)。因此,cellForRowAtIndexPath
将永远不会调用表视图的视图,并且由于没有行,所以也没有集合视图,因此numberOfItemsInSection
将永远不会调用它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句