UIScrollView的delegate方法妙用之讓UICollectionView滑動到某個你想要的位置,uiscrollviewdelegate

來源:互聯網
上載者:User

UIScrollView的delegate方法妙用之讓UICollectionView滑動到某個你想要的位置,uiscrollviewdelegate

一個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最終停止在目標位置。注意:scrollView的pagingEnable屬性必須為NO時這個方法才會被調用。 例:- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {    CGPoint orifinalTargetContentOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);    *targetContentOffset = [self  itemCenterOffsetWithOriginalTargetContentOffset:orifinalTargetContentOffset];//計算出想要其停止的位置  }這樣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的類中  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.