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