启用collectionview分页时将collection view滚动到索引

Posted

技术标签:

【中文标题】启用collectionview分页时将collection view滚动到索引【英文标题】:Scroll collection view to index when collectionview paging is enabled 【发布时间】:2016-03-16 04:39:12 【问题描述】:

我正在使用UICollectionView 并为其启用了分页功能。 例如,我在UICollectionView 中有 21 个项目,每页包含 7 个项目,所以共有 3 个页面...... 有没有办法scrollToItemAtIndexPath 仅当索引不在当前页面中时... 我正在使用下面的代码滚动每个索引的UICollectionView

[collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

【问题讨论】:

您希望滚动页面明智吗?每页包含 7 个项目,您想滚动到下 7 个项目对吗? 是的,我想滚动页面 是否有解决方案使每页只有七个项目?还是改成8个或6个? 【参考方案1】:

无论您的目标 indexPath 是否可见,您都可以使用collectionView.indexPathsForVisibleItems,然后在必要时滚动

【讨论】:

【参考方案2】:

试试这个,希望对你有帮助

先获取索引,然后通过除以每页的总项得到页面,然后使用页码滚动到可见的rect,例如,

- (IBAction)scroll:(id)sender
  
    int item = 89; //item to scroll (21 will be your case) and item might be any idea of cell
    int page = item/15; //15 is the total number of visible cell per page (7 will be your case)
    CGRect frameRect = self.collectionView.frame;
    CGFloat xPos = frameRect.origin.x + (frameRect.size.width * page); //calculate the position where that cell is present
    frameRect.origin.x = xPos;
   [self.collectionView scrollRectToVisible:frameRect animated:YES];//finally scroll the collection view
 

【讨论】:

以上是关于启用collectionview分页时将collection view滚动到索引的主要内容,如果未能解决你的问题,请参考以下文章

iOS:用于加载图像的 CollectionView 垂直分页

启用分页和每页多个单元格时奇怪的 UICollectionView 行为

如何通过 panGestureRecognizer 启用 collectionView 分页

在启用分页的情况下使两个 UICollectionView 同步滚动

计算哪个图像用户在水平集合视图上,启用分页

用于加载联系人的Phonegap Jquery Pagination - 当用户到达最后一页时如何动态添加页面?