2015-11-04 45 views
1

所以我有图像的colectionView,当东西在后台会发生,我可能会尝试使用该方法来选择特定的自定义collectionViewCell为什么在代码中选择单元格后,我的自定义集合意外地显示为零?

self.collectionView.selectItemAtIndexPath(indexPathToReload, animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredVertically),工作正常,在collectionView滚动到所需的位置。

但是,如果我然后尝试实际更新单元格的外观,因为它已通过调用self.collectionView(self.collectionView, didSelectItemAtIndexPath: indexPathToReload)进行更新,所以当我尝试在didSelectItemAtIndexPath中创建单元格时,出现意外的零单元格。

我部分明白,为什么更新细胞的这种方法是不安全的(因为我已经在研究类似here in one of the answers这个问题在其他地方阅读。)

因此,碰撞让我假设细胞是不可见的部分细胞在屏幕上,这就是为什么当我尝试创建它时单元格为零。但是这样做没有意义,因为我也假定必须创建单元格才能滚动到正确的位置,正如我所说的那样,罚款是因为它们按预期方式创建并且可以毫无问题地进行交互。

那么为什么我的细胞零?或者为什么我的集合视图不认为滚动到可见单元格的单元格?如果原因很明显,那么在代码中选择它时如何才能更新它的外观?

编辑:代码在上下文中

dispatch_async(dispatch_get_main_queue()) { 
    self.collectionView.selectItemAtIndexPath(indexPathToReload, animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredVertically) 
    self.collectionView(self.collectionView, didSelectItemAtIndexPath: indexPathToReload) 
    return 
} 

正如我已经说过了,这几乎是上下文。在第一行中,我可以滚动到屏幕上不可见的索引。如果我这样做,然后执行第二行代码,则在调用的委托方法中创建的单元格意外为零。

+0

分享一些你的代码,所以我们可以看到它在上下文。 –

+0

这几乎是上下文,但我会更新我的答案。 – pbush25

+0

调用'selectItemAtIndexPath'应该自动触发'didSelectItemAtIndexPath'上的调用。你为什么要调用它像'self.collectionView(self.collectionView,didSelectItemAtIndexPath:indexPathToReload)'? – Abhinav

回答

0

为了解决这个问题,我不得不使用一种哈克解决方法,虽然工作似乎太脏了,我不知道苹果为什么没有解决这个问题(即为什么selectItemAtIndexPath doesn拨打代表方式didSelectItemAtIndexPath)。不管怎么说,我落得这样做,当我需要在后台更新我选定单元格,我第一次拿到了指数,并设置一个布尔值,显示单元代码选择:

dispatch_async(dispatch_get_main_queue()) { 
    self.collectionView.selectItemAtIndexPath(indexPathToReload, animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredVertically) 
    let cell = self.collectionView.cellForItemAtIndexPath(indexPathToReload) as? ListingCollectionViewCell 
    if cell != nil { 
     self.collectionView(self.collectionView, didSelectItemAtIndexPath: indexPathToReload) 
     return 
    } else { 
     self.buttonSelectedInCode = true 
     self.indexPathSelectedInCode = indexPathToReload 
     return 
    } 
} 

以上,我不得不尝试为指定的索引路径创建单元格。如果单元格不是零,那么我知道单元格是可见的,并且可以安全地调用委托人didSelectItemAtIndexPath。但是,如果单元格为零,则必须设置我的布尔和索引,并等待滚动视图调用委托方法,如下所示。

然后,我进一步落实scrollViewDidEndScrollAnimation,并使用该委托方法的调用,然后选择我的码单元,具体如下:

func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { 
    if buttonSelectedInCode { 
     self.collectionView(self.collectionView, didSelectItemAtIndexPath: self.indexPathSelectedInCode) 
    } 
} 
相关问题