首页 > 解决方案 > 方法 scrollToItemAtIndexPath 不适用于 iOS 14

问题描述

scrollToItemAtIndexPath从 iOS 14 开始遇到问题。在以前的 iOS 版本中,当用户停止拖动时,下一个单元格水平居中,现在该方法 scrollToItemAtIndexPath被忽略,它仍然停留在第一个单元格中。

    - (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];

        }
    }
    
}

标签: iosios14collectionview

解决方案


您可以使用layoutAttributesForItem(at indexPath: IndexPath)UICollectionViewLayout计算适当的 contentOffset

修复可能是这样的:

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

推荐阅读