簡體   English   中英

Swift-如何根據整數中的索引位置從UICollectionView中獲取UICollectionViewCell

[英]Swift - How to fetch a UICollectionViewCell from UICollectionView based on index position in integer

我得到的數據索引為int。 我得到的數據位置可以是1或2或3或4 ..依此類推。 我如何使用這些int從collectionview獲取colletionviewcell。

在每個滾動的即時獲取單元格索引為int的情況下,例如,下一次滑動將為0,下一次滑動將為1,下一次滑動編號將為2,依此類推。

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
            let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
            var offset = targetContentOffset.pointee
            let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
            let roundIndex = round(index)
            offset = CGPoint(x: roundIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
            targetContentOffset.pointee = offset

for cell in collectionView.visibleCells as! [CaurosalCollectionViewCell] {
            // do something

            print(cell.title.text)
        }
    }

預期產量

您可以使用yourCollectionView?.indexPathsForVisibleItems,但它返回一個數組。 因此,您必須計算在當前contentOffset上可見的indexPath。

就像是:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: yourCollectionView.contentOffset, size: yourCollectionView.bounds.size)
    let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY))
    let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint)
}

編輯

您需要研究UICollectionViewLayout,尤其是layoutAttributesForItem(位於indexPath:IndexPath)。 您可以基於當前IndexPath更新布局,而無需通過scrollview委托。

如果您希望使用scollview委托,我相信這里的問題會得到更好的回答: 如何像在Spotify的Player中那樣創建居中的UICollectionView

您可以從該索引創建indexpath,並提供部分(我將其設為0)。 如果沒有部分,則為零。 此外,傳遞此索引路徑以獲取單元格,現在您必須將單元格轉換為所需的類型,然后才能使用它

 let indexpath = IndexPath(row: index, section: 0)
 guard let cell = collectionView.cellForItem(at: indexpath) as? CaurosalCollectionViewCell else { return }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM