2017-10-11 170 views
0

我得到的数据索引为int。我得到我的数据的位置可以是1或2或3或4 ..等等。我如何使用这些int从collectionview中获取colletionviewcell。Swift - 如何从UICollectionView中获取基于整数索引位置的UICollectionViewCell

在每个滚动我得到单元格的索引作为int例如初始它将为0下一次刷卡的数字将是1,下一次刷卡nos将是2等等。

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { 
      let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout 
      let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing 
      var offset = targetContentOffset.pointee 
      let index = (offset.x + scrollView.contentInset.left)/cellWidthIncludingSpacing 
      let roundIndex = round(index) 
      offset = CGPoint(x: roundIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top) 
      targetContentOffset.pointee = offset 

for cell in collectionView.visibleCells as! [CaurosalCollectionViewCell] { 
      // do something 

      print(cell.title.text) 
     } 
    } 

expected output

+0

要获取细胞在哪里?在滚动? – ahbou

+0

yes在scrollViewWillEndDragging –

+1

您无法检索该单元,因为它尚未显示在屏幕上。你能更具体地说明你想做什么? –

回答

1

您可以使用yourCollectionView?.indexPathsForVisibleItems但它返回一个数组。 所以你必须计算当前contentOffset中哪些indexPath是可见的。

喜欢的东西:

func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let visibleRect = CGRect(origin: yourCollectionView.contentOffset, size: yourCollectionView.bounds.size) 
    let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY)) 
    let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint) 
} 

编辑

你需要寻找到UICollectionViewLayout特别layoutAttributesForItem(在indexPath:IndexPath)。您可以根据当前的IndexPath更新布局,而无需通过scrollview委托。

如果您希望使用scollview委托我相信这个问题是更好地在这里回答:How to create a centered UICollectionView like in Spotify's Player

+0

我已经更新了我的func,我需要根据roundIndex获取单元格。我得到“不能将类型'CGFloat'的值转换为期望的参数类型'CGPoint'”我没有CGPoint我正在调整中心的水平collectionview单元格,我需要增加它的z位置 –

+0

你可以检查我的代码我可以根据roundIndex变量来获取单元格 –

0

您可以从该指数创造indexpath,提供部分(我把它0)。如果没有部分,那么它是零。此外,通过这个indexpath获取细胞, 现在你必须强制转换的细胞成所需要的类型,那么你可以使用它

let indexpath = IndexPath(row: index, section: 0) 
guard let cell = collectionView.cellForItem(at: indexpath) as? CaurosalCollectionViewCell else { return } 
+0

我无法获取我的单元格它总是在返回语句中 –