UICollectionView自动滚动分页

Erk*_*CET 1 paging scroll uicollectionview

我的项目有一个UIcollectionView.这个水平分页有四个对象.我想要我的collectionView Auto Scroll Paging.哪种使用方法?

Eli*_*Lam 11

至于理论,我只是解释了关键点.例如,如果您想在某处自动循环显示5张图像,就像广告栏一样.您可以创建一个包含100个部分的UICollectionView,每个部分中有5个项目.创建UICollectionView后,将其原始位置设置为等于第50个第0个项目(MaxSections的中间),以便您可以向左或向右滚动.不要担心它会结束,因为我在Timer运行时将位置重置等于MaxSections的中间位置.永远不要和我争辩:"当用户继续自己滚动时它也将结束"如果一个人发现只有5个图像,他会不断滚动!?我相信这个世界上很少有这么傻的用户!

注意:在以下代码中,headerView是UICollectionView,headerNews是数据.我建议设置MaxSections = 100.

在自定义collectionView之后添加NSTimer(确保首先正确设置了UICollectionViewFlowLayout):

    - (void)addTimer
    {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        self.timer = timer;

}
Run Code Online (Sandbox Code Playgroud)

然后实现@selector(nextPage):

 - (void)nextPage
{
    // 1.back to the middle of sections
    NSIndexPath *currentIndexPathReset = [self resetIndexPath];

    // 2.next position 
    NSInteger nextItem = currentIndexPathReset.item + 1;
    NSInteger nextSection = currentIndexPathReset.section;
    if (nextItem == self.headerNews.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];

    // 3.scroll to next position
    [self.headerView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

最后实现resetIndexPath方法:

- (NSIndexPath *)resetIndexPath
{
    // currentIndexPath
    NSIndexPath *currentIndexPath = [[self.headerView indexPathsForVisibleItems] lastObject];
    // back to the middle of sections
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:MaxSections / 2];
    [self.headerView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    return currentIndexPathReset;
}
Run Code Online (Sandbox Code Playgroud)

为了控制NSTimer,您必须实现一些其他方法和UIScrollView的委托方法:

- (void)removeTimer
{
    // stop NSTimer 
    [self.timer invalidate];
   // clear NSTimer
    self.timer = nil;
}

// UIScrollView' delegate method
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
        [self removeTimer];
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
        [self addTimer];

}
Run Code Online (Sandbox Code Playgroud)