我试图通过使用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")
}
索引路径始终为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的子类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句