swift获取collectionView中心cell的indexPath?

Get the indexPath of cell in the center of collectionView in swift?

我试过使用 uicollectionview 的扩展来获取集合视图中心单元格的索引,但我总是得到 nil 而不是索引。我该如何解决这个问题?

extension UICollectionView {
    var centerPoint : CGPoint {
        get {
            return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
        }
    }

    var centerCellIndexPath: NSIndexPath? {
        if let centerIndexPath: NSIndexPath  = self.indexPathForItemAtPoint(self.centerPoint) {
            return centerIndexPath
        }

        return nil
    }
}

然后:在随机方法的 UIViewController 中我有这个:

if let centerCellIndexPath: NSIndexPath  = collectionTemp!.centerCellIndexPath {
    print(centerCellIndexPath)
} else {
    println("nil")
}

索引路径始终为零,我不明白为什么,因为单元格按顺序显示,除此之外一切正常。

我已经设法通过使用始终将单元格置于中心的自定义布局解决了我的问题。使用这个中心的 indexPath 永远不会为零。

 class CenterFlowLayout: UICollectionViewFlowLayout {

 override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
     if let cv = self.collectionView {
        let cvBounds = cv.bounds
        let halfWidth = cvBounds.size.width * 0.5
        let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth
     if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) as [UICollectionViewLayoutAttributes]! {
        var candidateAttributes: UICollectionViewLayoutAttributes?
        for attributes in attributesForVisibleCells {
      // == Skip comparison with non-cell items (headers and footers) == //
      if attributes.representedElementCategory != UICollectionElementCategory.Cell {
        continue
      }
      if let candAttrs = candidateAttributes {
        let a = attributes.center.x - proposedContentOffsetCenterX
        let b = candAttrs.center.x - proposedContentOffsetCenterX
            if fabsf(Float(a)) < fabsf(Float(b)) {
               candidateAttributes = attributes
            }
      } else { // == First time in the loop == //
        candidateAttributes = attributes
        continue
      }
    }
    return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y)
  }
}
// Fallback
    return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
 }
}

将其添加为 UICollectionFlowLayout 的子类。