如何在Swift中获取CollectionView中居中单元格的indexPath?

6

我尝试使用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
这个有更新了吗? - Joel García Verástica
1个回答

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的子类。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接