Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix reuse scrollToItem: to mask the bug of inaccurate scroll position,避免重复scrollToItem #38

Open
Benzoudeliuxing opened this issue May 17, 2023 · 0 comments

Comments

@Benzoudeliuxing
Copy link

Benzoudeliuxing commented May 17, 2023

避免重复scrollToItem
fix reuse scrollToItem: to mask the bug of inaccurate scroll position

collectionView.scrollToItem(at: indexPath,
                                        at: scrollPosition,
                                        animated: animated)
collectionView.scrollToItem(at: indexPath,
                                        at: scrollPosition,
                                        animated: animated)
func scrollToIndexPath(
        _ indexPath: IndexPath, animated: Bool) {
        
        if params.isPagingEnabled {
            
            let itemCount = collectionView.numberOfItems(inSection: indexPath.section)
            
            let itemWidth = layout.itemSize.width
            let itemHeight = layout.itemSize.height
            
            
            if layout.params?.scrollDirection == .vertical {
                let sectionSpacing = layout.sectionInset.left + layout.sectionInset.right
                let itemSpacing = layout.minimumLineSpacing

                let sectionHeight = CGFloat(indexPath.section) * (itemHeight + itemSpacing) * CGFloat(itemCount)
                let verticalOffset = sectionHeight + sectionSpacing / 2 + (itemHeight + itemSpacing) * CGFloat(indexPath.item) - collectionView.bounds.height / 2 + itemHeight / 2
                let offset = CGPoint(x: 0, y: verticalOffset)
                collectionView.setContentOffset(offset, animated: animated)
            }else {
                let sectionSpacing = layout.sectionInset.top + layout.sectionInset.bottom
                let itemSpacing = layout.minimumInteritemSpacing
                let sectionWidth = CGFloat(indexPath.section) * (itemWidth + itemSpacing) * CGFloat(itemCount)
                let horizontalOffset = sectionWidth + sectionSpacing / 2 + (itemWidth + itemSpacing) * CGFloat(indexPath.item) - collectionView.bounds.width / 2 + itemWidth / 2
                let offset = CGPoint(x: horizontalOffset, y: 0)
                collectionView.setContentOffset(offset, animated: animated)
            }
        }
    }
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant