温馨提示:本文翻译自stackoverflow.com,查看原文请点击:objective c - How to scroll UICollectionViewCell programmatically in IOS?
ios objective-c uicollectionview uicollectionviewcell uiscrollview

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

发布于 2020-03-29 21:41:17

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

我试过使用:

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

和:

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

它们可以工作,但是它们会暂时“遮盖”当前单元格以显示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))];

哪里_currentIndexRowForCellOnScreenindexPath.row对的UICollectionView的屏幕上的首次亮相:

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

但是当我把它放进去时:

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

它在第一个Cell之后返回NULL,并且不设置动画。

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

查看更多

提问者
Rhotick
被浏览
126
MDB983 2014-02-04 12:07

假设您的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];