David Vittori
David Vittori

Reputation: 1196

Method scrollToItemAtIndexPath is not working on iOS 14

I am having an issue with scrollToItemAtIndexPath from iOS 14. In the previous iOS versions when the user stopped dragging, the next cell was centered horizontally, now the method scrollToItemAtIndexPath is ignored, and it remains stuck in the first cell.

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    if( scrollView.tag == 1 ) {
        if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad){
            *targetContentOffset = scrollView.contentOffset; // set acceleration to 0.0
            float pageWidth = (float) (self.view.frame.size.width)-80;
            int minSpace = 10;
            
            int cellToSwipe = (scrollView.contentOffset.x)/(pageWidth + minSpace) + (velocity.x < 0 ? 0 : 1); // cell width + min spacing for lines
            if (cellToSwipe < 0) {
                cellToSwipe = 0;
            } else if (cellToSwipe >= MIN(6, self.news.count )) {
                cellToSwipe = (int) MIN(6, self.news.count);
            }
            [self.newsCollectionView scrollToItemAtIndexPath: [NSIndexPath indexPathForRow:cellToSwipe inSection:0]
                                            atScrollPosition: UICollectionViewScrollPositionCenteredHorizontally
                                                    animated: YES];

        }
    }
    
}

Upvotes: 2

Views: 1199

Answers (4)

mlibai
mlibai

Reputation: 31

_collectionView.pagingEnabled = NO;
[_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionLeft) animated:NO];
_collectionView.pagingEnabled = YES;

Upvotes: 1

Jerrin
Jerrin

Reputation: 181

Objective-C version:

UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:section]];
                
[collectionView setContentOffset:attributes.frame.origin animated:YES];

where collectionView is your UICollectionView object, index is the row of the UICollectionView to which you want to scroll to and section is the section of the UICollectionView to which the row belongs to.

Upvotes: 2

Anton Poderechin
Anton Poderechin

Reputation: 66

You can use layoutAttributesForItem(at indexPath: IndexPath) of the UICollectionViewLayout to calculate a proper contentOffset

The fix could be like that:

extension UICollectionView {
    func scrollTo(indexPath: IndexPath) {
        let attributes = collectionViewLayout.layoutAttributesForItem(at: indexPath)!
        setContentOffset(attributes.frame.origin, animated: true)
    }
}

Upvotes: 4

阿斯蒂芬
阿斯蒂芬

Reputation: 21

scrollToItemAtIndexPath still has some problems on iOS 14, you can use setContentOffsetinstead, and it works for me.

Upvotes: 2

Related Questions