項(xiàng)目中有個(gè)地方需要按頁(yè)滑動(dòng)姥份,想了幾種方法都沒(méi)有好好的實(shí)現(xiàn)。用系統(tǒng)提供的pagingEnabled需要視圖寬高和屏幕一致年碘,效果才理想澈歉。
但在項(xiàng)目中看到前人的實(shí)現(xiàn),居然可以完美的實(shí)現(xiàn)屿衅,很驚訝埃难,就研究下了下。
- (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()
這個(gè)是關(guān)鍵,沒(méi)有的話沒(méi)有效果涡尘。- (**void**)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(**inout** CGPoint *)targetContentOffset
這個(gè)方法中也可以實(shí)現(xiàn)同樣的效果忍弛。
經(jīng)過(guò)打印發(fā)現(xiàn):
- 異步block中代碼開(kāi)始執(zhí)行在
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
方法之后,在- (**void**)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
之前考抄。結(jié)束在這個(gè)方法之后 -
scrollViewDidEndDecelerating
方法執(zhí)行后runloop立即退出剧罩,可以推斷是mode切換了,因?yàn)榛瑒?dòng)結(jié)束了 - 當(dāng)有異步block中scrollToItemAtIndexPath方法時(shí)座泳,
scrollViewDidEndDecelerating
的調(diào)用時(shí)機(jī)提前了很多,runloop不會(huì)再處理source0和timer事件幕与,也不會(huì)休眠挑势,而是立即退出
異步block我們可以理解為在- (**void**)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(**BOOL**)decelerate
這個(gè)方法之后執(zhí)行代碼,不加異步是在方法中啦鸣。在這個(gè)方法之后調(diào)用- (**void**)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(**BOOL**)animated;
潮饱,會(huì)停止減速,相當(dāng)于加速減速過(guò)程诫给,瞬間完成香拉,并且沒(méi)有滑動(dòng)的距離。