在swift中获取collectionView中心的cell的indexPath?

时间:2015-05-05 18:06:01

标签: ios swift uicollectionview uicollectionviewcell nsindexpath

我试过这个,通过使用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")
}

索引路径总是为零,我不明白为什么,因为单元格按顺序显示,除此之外一切都很好。

1 个答案:

答案 0 :(得分:2)

我设法通过使用始终将单元格保持在中心的自定义布局来解决我的问题。使用它,中心的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的子类。