5

Tôi đã thử cách này để lấy chỉ mục của ô ở giữa chế độ xem bộ sưu tập bằng cách sử dụng phần mở rộng của uicollectionview, nhưng tôi luôn nhận được số không thay vì chỉ mục. Làm thế nào tôi có thể sửa lỗi này?Lấy indexPath của ô ở trung tâm của collectionView nhanh chóng?

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

sau đó: trong một UIViewController trong một phương pháp ngẫu nhiên tôi có điều này:

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

con đường chỉ số luôn luôn là con số không, và tôi không nhận được nó tại sao, bởi vì các tế bào hiển thị theo thứ tự, mọi thứ đều ổn, ngoại trừ điều này.

+1

mọi cập nhật về điều này? –

Trả lời

2

Tôi đã cố gắng giải quyết vấn đề của mình bằng cách sử dụng bố cục tùy chỉnh luôn giữ một ô ở giữa. Sử dụng indexPath này ở trung tâm không bao giờ có thể là nil.

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

Thêm trường này làm lớp con của UICollectionFlowLayout.

Các vấn đề liên quan