美文网首页
自己实现pageEnable

自己实现pageEnable

作者: 学习无底 | 来源:发表于2019-07-21 10:05 被阅读0次

项目中有个地方需要按页滑动,想了几种方法都没有好好的实现。用系统提供的pagingEnabled需要视图宽高和屏幕一致,效果才理想。

但在项目中看到前人的实现,居然可以完美的实现,很惊讶,就研究下了下。

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.start = scrollView.contentOffset.x;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"decelerate:%d", decelerate);
    self.end = scrollView.contentOffset.x;

    NSInteger index = self.index;
    if (self.end - self.start >= 20) {
        index++;
    }else if (self.start - self.end >= 20) {
        index--;
    }

    if (index < 0) {
        index = 0;
    }
    if (index >= 10) {
        index = 9;
    }
    self.index = index;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    });
}

dispatch_async(dispatch_get_main_queue()这个是关键,没有的话没有效果。- (**void**)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(**inout** CGPoint *)targetContentOffset这个方法中也可以实现同样的效果。

经过打印发现:

  • 异步block中代码开始执行在- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate方法之后,在- (**void**)scrollViewDidEndDecelerating:(UIScrollView *)scrollView之前。结束在这个方法之后
  • scrollViewDidEndDecelerating方法执行后runloop立即退出,可以推断是mode切换了,因为滑动结束了
  • 当有异步block中scrollToItemAtIndexPath方法时,scrollViewDidEndDecelerating的调用时机提前了很多,runloop不会再处理source0和timer事件,也不会休眠,而是立即退出

异步block我们可以理解为在- (**void**)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(**BOOL**)decelerate这个方法之后执行代码,不加异步是在方法中。在这个方法之后调用- (**void**)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(**BOOL**)animated;,会停止减速,相当于加速减速过程,瞬间完成,并且没有滑动的距离。

相关文章

  • 自己实现pageEnable

    项目中有个地方需要按页滑动,想了几种方法都没有好好的实现。用系统提供的pagingEnabled需要视图宽高和屏幕...

  • CollectionView pageEnable 实现

    参考文章的collectionView pageEnable 实现https://www.jianshu.com/...

  • CollectionView pageEnable 自定义实现

    方式一 (实现scrollView的代理较为通用) 方式二 (自定义UICollectionViewFlowLay...

  • iOS 自定义 UIScrollerView的PageSize大

    前言: UIScrollerView 设置PageEnable,每页滚动的偏移量是 UIScrollerView的...

  • UICollectionView 分页效果

    1、分页宽度和屏幕宽度相等:设置PageEnable为YES即可;2、分页宽度和屏幕宽度不相等:自定义FlowLa...

  • UIScrollView pageEnable时候自定义page

    转载两篇文章 Changing the size of a paging scroll viewPaging a ...

  • 实现自己

    人一辈子都在寻找自己,怎么去寻找自己呢?“自我实现的预言”原来是指我们平时所说的话,可能会成为他自己的生命预言。”...

  • 认识自己,实现自己

    听过一句话说:人这一生,最难的是看清自己。 看清自己适合什么工作 这个世界上,每个人都有自己擅长的和不擅长的事物。...

  • 自己实现AJAX

    1. JS操作请求与响应 1.1 JS 可以设置任意请求 header 吗? 可以 第一部分 re...

  • 自己实现ArrayList

    ArrayList最重要的基本方法Api: set(int idx, AnyType newVak) 向目标索引i...

网友评论

      本文标题:自己实现pageEnable

      本文链接:https://www.haomeiwen.com/subject/trlmlctx.html