如何在IOS中以编程方式滚动UICollectionViewCell?

我有一个垂直的UICollectionView,每个单元格占据整个self.view.frame我可以轻松地向上滑动到页面到下一个单元格,但我想要做同样的事情,按一个按钮.

我试过使用:

- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated

和:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated

他们工作,但他们暂时“白掉”当前的Cell来呈现nextCell,而滑动在转换期间显示两个单元格.

理想情况下,我想使用:

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated

但是我不知道如何访问nextCell的indexPath …
我试过了:

NSIndexPath *nextIndexPath = [_collectionView indexPathForItemAtPoint:CGPointMake(25,(_collectionView.frame.size.height-25)*(_currentIndexRowForCellOnScreen+1))];

其中_currentIndexRowForCellOnScreen是UICollectionView在屏幕上的第一个外观的indexPath.row:

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

但是当我把它放到:

- (NSIndexPath *)indexPathForCell:(UICollectionViewCell *)cell

它在第一个单元格之后返回NULL,而不是动画….

任何方向都将不胜感激.感谢您的时间.

解决方法

假设你的collectionView只包含1个部分,并且假定每个项目占据整个框架,那么你可以做这样的事情;
NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
  NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
  NSIndexPath *nextItem = [NSIndexPath indexPathForItem:currentItem.item + 1 inSection:currentItem.section];
  [self.collectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...