ArisRS
ArisRS

Reputation: 1394

UICollectionView with UICollectionViewCompositionalLayout scrollToItem doesn't work

I have horizontal UICollectionView with UICollectionViewCompositionalLayout and orthogonalScrollingBehavior = .groupPagingCentered, created like this:

    private lazy var compositionalLayout = UICollectionViewCompositionalLayout(sectionProvider: { [weak self] (_: Int, _: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in

    guard let self else { return nil }
    let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(self.cellWidth), heightDimension: .absolute(Const.Layout.itemSize.height))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    item.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

    let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(self.cellWidth), heightDimension: .absolute(Const.Layout.itemSize.height))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
    // group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

    let section = NSCollectionLayoutSection(group: group)
    section.orthogonalScrollingBehavior = .groupPagingCentered
    section.visibleItemsInvalidationHandler = { [weak self] (_, _, _) in
        guard let self else { return }
        let center = self.contentView.convert(self.collectionView.center, to: self.collectionView)
        guard let indexPath = self.collectionView.indexPathForItem(at: center) else { return }
        .... // Item change handler
    }
    return section
})

I need to scroll for exact item in my collection view, so I am trying:

collectionView.scrollToItem(at: IndexPath(row: indexOfItem, section: 0), at: .centeredHorizontally, animated: false)

but it is scrolling to wrong item.

Upvotes: 0

Views: 33

Answers (0)

Related Questions