Ios UICollectionView indexPathsForVisibleItems在某些情况下不起作用
我有一个UICollectionView,每个页面都与屏幕大小完全相同。滚动方向是水平的。我想在视图滚动时获取当前可见单元格 例如,如果我在一个整页上,我只得到这个页面的索引,如果我在两个页面中间滚动,那么我可以得到这两个页面索引。我知道有Ios UICollectionView indexPathsForVisibleItems在某些情况下不起作用,ios,objective-c,uicollectionview,Ios,Objective C,Uicollectionview,我有一个UICollectionView,每个页面都与屏幕大小完全相同。滚动方向是水平的。我想在视图滚动时获取当前可见单元格 例如,如果我在一个整页上,我只得到这个页面的索引,如果我在两个页面中间滚动,那么我可以得到这两个页面索引。我知道有indexPathsForVisibleItems方法。它适用于在中间滚动的情况。它将返回两个单元格的索引 但是如果我在一整页上,它也会返回两页。更奇怪的是,这种情况发生在我的iPhone7Plus上,但当我在iPhone6S上测试它时,它工作正常并返回当前页
indexPathsForVisibleItems
方法。它适用于在中间滚动的情况。它将返回两个单元格的索引
但是如果我在一整页上,它也会返回两页。更奇怪的是,这种情况发生在我的iPhone7Plus上,但当我在iPhone6S上测试它时,它工作正常并返回当前页面的单个索引
这种方法似乎不适用于大屏幕
我的收藏视图:
CGSize screenSize = [UIScreen mainScreen].fixedBounds.size;
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumLineSpacing = 0.0;
flowLayout.minimumInteritemSpacing = 0.0;
flowLayout.itemSize = screenSize;
UIColloctionView *collectionView =
[[UICollectionView alloc] initWithFrame:SCRectMakeWithSize(screenSize) collectionViewLayout:flowLayout];
collectionView.backgroundColor = [UIColor clearColor];
collectionView.scrollsToTop = NO;
collectionView.pagingEnabled = YES;
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.showsVerticalScrollIndicator = NO;
我用于获取当前可见索引的方法:
NSArray<NSIndexPath *> *indexPaths = [_tabsCollectionView indexPathsForVisibleItems];
NSArray*indexPaths=[[选项卡集合视图indexPathsForVisibleItems];
在更大的屏幕上,当我查看整个页面时,这将返回2个项目。即使我面临类似类型的问题 下面是对我有效的解决方法 Swift 3解决方案
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let visibleIndexPath: IndexPath = collectionView.indexPathForItem(at: visiblePoint) else { return }
print(visibleIndexPath)
希望此解决方案对您有效。一些相关代码会有所帮助。我不知道您的问题,但另一个解决方法可能是检查滚动偏移量以检索索引。如果只有一个节、多行或每节一行,则更容易。