【问题标题】:Get the indexPath of cell in the center of collectionView in swift?快速获取collectionView中心单元格的indexPath?
【发布时间】:2015-05-05 18:06:00
【问题描述】:

我已经尝试通过使用 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")
}

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

【问题讨论】:

  • 这方面有什么更新吗?

标签: ios swift uicollectionview uicollectionviewcell nsindexpath


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多