问题描述
我在iOS 14中遇到scrollToItemAtIndexPath
的问题。
在以前的iOS版本中,当用户停止拖动时,下一个单元格水平居中,现在方法scrollToItemAtIndexPath
被忽略,并且停留在第一个单元格中。
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVe@R_502_5707@ty:(CGPoint)ve@R_502_5707@ty 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) + (ve@R_502[email protected] < 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];
}
}
}
解决方法
您可以使用layoutAttributesForItem(at indexPath: IndexPath)
中的UICollectionViewLayout
来计算适当的contentOffset
修复可能是这样的:
extension UICollectionView {
func scrollTo(indexPath: IndexPath) {
let attributes = collectionViewLayout.layoutAttributesForItem(at: indexPath)!
setContentOffset(attributes.frame.origin,animated: true)
}
}
,
scrollToItemAtIndexPath
在iOS 14上仍然存在一些问题,您可以改为使用setContentOffset
,它对我有用。
Objective-C版本:
UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:section]];
[collectionView setContentOffset:attributes.frame.origin animated:YES];
其中 collectionView 是您的UICollectionView对象,索引是您要滚动到的UICollectionView的行,而 section 是该部分该行所属的UICollectionView的视图。
,_collectionView.pagingEnabled = NO;
[_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionLeft) animated:NO];
_collectionView.pagingEnabled = YES;