5

Ho provato questo per ottenere l'indice di una cella al centro di una vista insieme utilizzando un'estensione di uicollectionview, ma ottengo sempre nil invece dell'indice. Come posso risolvere questo?Ottieni il indexPath della cella nel centro di collectionView in swift?

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 
    } 
} 

poi: in un UIViewController in un metodo casuale ho questo:

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

il percorso indice è sempre pari a zero, e non farlo perché, perché le cellule vengono visualizzati in ordine, va tutto bene tranne questo

+1

eventuali aggiornamenti su questo? –

risposta

2

Sono riuscito a risolvere il mio problema utilizzando un layout personalizzato che mantiene sempre una cella al centro. Usando questo indexPath al centro non può mai essere nullo.

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) 
} 
} 

Aggiungere questo come sottoclasse di UICollectionFlowLayout.