Stack Overflow Asked by David Vittori on January 7, 2021
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)
}
}
Correct answer by Anton Poderechin on January 7, 2021
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.
Answered by Jerrin on January 7, 2021
scrollToItemAtIndexPath
still has some problems on iOS 14, you can use setContentOffset
instead, and it works for me.
Answered by 阿斯蒂芬 on January 7, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP