一个UICollectionView有好多个cell,滑动一下,谁也不知道会停留在哪个cell,滑的快一点,就会多滑一段距离,反之则会滑的比较近,这正是UIScrollview用户体验好的地方。
如果想要UICollectionView停留到某个cell的位置,可以用
- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;
这个方法,还能用scrollPosition这个参数控制cell具体停留在上下左右中到底哪个位置。
那么问题来了:如果我只是随便滑了一下,我也不知道它会停在位于哪个indexPath的cell上,但不管它停在哪个cell上,我都希望这个cell刚好在屏幕中间,应该怎么办呢?(这个场景在coverFlow的效果里比较常见)
 
之前知道的做法是:
在scrollViewDidEndDecelerating或其他delegate方法里,通过当前 contentOffset 计算最近的整数页及其对应的 contentOffset,然后通过动画移动到这个位置。
但是这个做法有问题,就是动画不连贯,完全没有“刚好停到那里”的感觉。
 
今天在想有没有其他更好的办法时,突然发现一个之前从来没用功的方法:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0);
一看这参数名,再看看这文档,真是让人喜不自禁呐!这不就是让scrollView“刚好停到某个位置”的方法嘛!!!(系统5.0就提供了,现在才看到。。。。。。)
targetContentOffset 是个指针,可以修改这个参数的值,让scrollView最终停止在目标位置。
(2016年12月7日更新)
注意:scrollView的pagingEnable属性必须为NO时这个方法才会被调用。
感谢@ ZeroOnet 评论中指出,这个方法在pagingEnable==YES的时候也会调用;
但是pagingEnable的效果会覆盖这个方法的效果,达不到我们想要的“刚好停到指定位置的效果”,所以还是需要注意将pagingEnable设置为NO!
 
例:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGPoint originalTargetContentOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);
    CGPoint targetCenter = CGPointMake(originalTargetContentOffset.x + CGRectGetWidth(self.collectionView.bounds)/2, CGRectGetHeight(self.collectionView.bounds) / 2);
    NSIndexPath *indexPath = nil;
    NSInteger i = 0;
    while (indexPath == nil) {
        targetCenter = CGPointMake(originalTargetContentOffset.x + CGRectGetWidth(self.collectionView.bounds)/2 + 10*i, CGRectGetHeight(self.collectionView.bounds) / 2);
        indexPath = [self.collectionView indexPathForItemAtPoint:targetCenter];
        i++;
    }
    self.selectedIndex = indexPath;
    //这里用attributes比用cell要好很多,因为cell可能因为不在屏幕范围内导致cellForItemAtIndexPath返回nil
    UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
    if (attributes) {
        *targetContentOffset = CGPointMake(attributes.center.x - CGRectGetWidth(self.collectionView.bounds)/2, originalTargetContentOffset.y);
    } else {
        DLog(@"center is %@; indexPath is {%@, %@}; cell is %@",NSStringFromCGPoint(targetCenter), @(indexPath.section), @(indexPath.item), attributes);
    }
   
}
 
这样scrollView就会逐渐减速,最终停止在itemCenterOffsetWithOriginalTargetContentOffset方法算出来的位置上了,效果杠杠的~
 
本来以为这个方法没多少人知道,结果百度一搜,发现原来已经有大神写过详细的文章了(http://tech.glowing.com/cn/practice-in-uiscrollview/),这个就当记录一下吧
 

另外发现一个直接用NSObject就实现类似效果的库:https://github.com/nicklockwood/iCarousel   乍看之下没看懂。。。等有空再仔细研究
 
更新(2015-06-19)
原来UICollectionViewLayout已经提供了两个方法可以实现这个功能:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity;
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset NS_AVAILABLE_IOS(7_0);
效果与上面的delegate方法完全一样,不过这个是UICollectionViewLayout的方法,需要在自己的layout子类里重载。
好处是:这样就不用再在viewController里写scrollView的delegate方法了,viewController更加简洁;跟布局相关的代码都转移到了layout的类中 

UIScrollView的delegate方法妙用之让UICollectionView滑动到某个你想要的位置的更多相关文章

  1. 在UIScrollView的delegate方法判断滚动快慢

    // 这里做预加载 CGPoint currentOffset = scrollView.contentOffset; NSTimeInterval currentTime = [NSDate tim ...

  2. UIScrollView和delegate的通信

    在OC中,发送消息的意思就是调用方法 因此UIScrollView和delegate的通信可以理解为下图所示 再精确一点,UIScrollView和delegate的通信应该为下图所示 可以看出,要想 ...

  3. jQuery事件绑定on()、bind()与delegate() 方法详解

    jquery中有四种事件绑定函数,bind(),live(),on(),delegate(),由于live现在并不常用,因此不做过多解释. 1. bind()用法 $("div p" ...

  4. jQuery(一)delegate() 方法

    定义和用法 delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数. 使用 delegate() 方法的事件处理程序适用于当前或未来 ...

  5. jQuery delegate方法实现Ajax请求绑定事件不丢失

    给元素绑定click事件后 ,遇到一个问题:当执行一些ajax请求,再次调用此页面,里面的这个click事件就失效了 比如说:我的分页是一个ajax请求 但我点下一页时 后生成的元素a就没有了clic ...

  6. Swift基础之Delegate方法的使用

    本文简单介绍了使用Delegate方法的进行值的传递,改变上一个界面的字体大小和颜色 首先创建一个导航视图: let viewC = ViewController();        let navi ...

  7. Block代替delegate,尽量使用block,对于有大量的delegate方法才考虑使用protocol实现.

    Block代替delegate,尽量使用block,对于有大量的delegate方法才考虑使用protocol实现. 1.Block语法总结及示例如下:         //1.普通代码块方式bloc ...

  8. jQuery 事件 - delegate() 方法

    <html><head><script type="text/javascript" src="/jquery/jquery.js" ...

  9. jquery的delegate()方法

    delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数. 使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如 ...

随机推荐

  1. 在usercontrol里实现导航

    (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/NewContent.xaml&qu ...

  2. 深入理解DOM节点类型第四篇——文档片段节点DocumentFragment

    × 目录 [1]特征 [2]作用 前面的话 在所有节点类型中,只有文档片段节点DocumentFragment在文档中没有对应的标记.DOM规定文档片段(document fragment)是一种“轻 ...

  3. .Net 转战 Android 4.4 日常笔记(2)--HelloWorld入门程序

    我不知道人们为什么那么喜欢用HelloWorld来做为自己的第一个程序入门,为什么不是hello **其他的东西或者hi. 一.打开ADT 的Eclipse开发工具新建一个Android项目 New- ...

  4. MySQL学习笔记八:日期/时间的处理

    MySQL日期时间的处理,在其官网文档上都有详细的阐述,想了解更多的同学可自行查阅. 1.查询当前日期时间:函数有now(),localtime(),current_timestamp(),sysda ...

  5. c# 实现简单的socket通信

    服务端 using System.Net.Sockets; using System.Net; using System.Threading; namespace SocketServer { cla ...

  6. 性能测试工具Locust

    An open source load testing tool. 一个开源性能测试工具. define user behaviour with python code, and swarm your ...

  7. 将richTextBox中的内容写入txt文件发现不换行(解决方法),在richTextBox指定位置插入文字

    string pathname = dt.ToString().Replace(":", ""); string str = richTextBoxResult ...

  8. JS实现输入框只能输入数字

    键盘下落事件实现输入框只能输入数字: <script type="text/javascript"> // 实现输入框只能输入数字 function ValidateN ...

  9. jackson error 含义log

    1. 反序列化失败,类型不匹配 Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserial ize ...

  10. gradle中使用嵌入式(embedded) tomcat, debug 启动

    在gradle项目中使用embedded tomcat. 最开始部署项目需要手动将web项目打成war包,然后手动上传到tomcat的webapp下,然后启动tomcat来部署项目.这种手动工作通常还 ...