iOS开发手写分页

#pragma mark -
//当用户开始拖拽的时候就调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeNSTimer];
}
//当用户停止拖拽的时候调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addNSTimer];
}
//设置页码
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page;
    if (self.aBanner.count) {
         page = (NSInteger)(scrollView.contentOffset.x/scrollView.frame.size.width+0.5) % self.aBanner.count;
    }
    self.pageControl.currentPage = page;
}

#pragma mark -
//添加定时器
- (void)addNSTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:TimeInterval
                                                      target:self
                                                    selector:@selector(nextPage)
                                                    userInfo:nil
                                                     repeats:YES];
    //添加到runloop中
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    self.timerN = timer;
}

//删除定时器
- (void)removeNSTimer
{
    [self.timerN invalidate];
    self.timerN = nil;
}

//自动滚动
- (void)nextPage
{
    //1获取当前正在展示的位置
    NSIndexPath *currentIndexPath=[[self.collectionView indexPathsForVisibleItems]lastObject];
    
    //马上显示回最中间那组的数据
    NSIndexPath *currentIndexPathRest=[NSIndexPath indexPathForItem:currentIndexPath.item
                                                          inSection:YYMaxSections/2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathRest
                                atScrollPosition:UICollectionViewScrollPositionLeft
                                        animated:NO];
    
    //2计算出下一个需要展示的位置
    NSInteger nextItem=currentIndexPathRest.item+1;
    NSInteger nextSection=currentIndexPathRest.section;
    if (nextItem == self.aBanner.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath=[NSIndexPath indexPathForItem:nextItem
                                                   inSection:nextSection];
    
    //3通过动画滚动到下一个位置
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath
                                atScrollPosition:UICollectionViewScrollPositionLeft
                                        animated:YES];
    
    //4)设置页码
    self.pageControl.currentPage = nextItem;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值