5

Próbowałem tego, aby uzyskać indeks komórki w centrum widoku kolekcji przy użyciu rozszerzenia widoku koligacji, ale ja zawsze otrzymuję zero zamiast indeksu. Jak mogę to naprawić?Pobierz indexPath komórki w centrum kolekcjiWygląd w szybkim tempie?

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

następnie: w UIViewController w metodzie losowej mam to:

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

ścieżka indeks jest zawsze zero, a ja nie rozumiem dlaczego, ponieważ komórki są wyświetlane w kolejności, wszystko jest w porządku oprócz tego.

+1

jakiekolwiek aktualizacje w tej sprawie? –

Odpowiedz

2

Udało mi się rozwiązać problem za pomocą niestandardowego układu, który zawsze utrzymuje komórkę w środku. Korzystanie z tej właściwości indexPath w centrum nigdy nie może być zerowe.

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

Dodaj to jako podklasę UICollectionFlowLayout.

Powiązane problemy