3 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
確定方向相當(dāng)簡(jiǎn)單,但請(qǐng)記住,方向可以在手勢(shì)過(guò)程中多次改變。例如,如果您有一個(gè)打開分頁(yè)的滾動(dòng)視圖,并且用戶滑動(dòng)以轉(zhuǎn)到下一頁(yè),則初始方向可能是向右的,但如果您打開了彈跳,它將暫時(shí)完全沒(méi)有方向然后簡(jiǎn)單地向左走。
要確定方向,您需要使用UIScrollView scrollViewDidScroll
委托。在這個(gè)示例中,我創(chuàng)建了一個(gè)名為變量的變量lastContentOffset
,用于將當(dāng)前內(nèi)容偏移量與前一個(gè)內(nèi)容偏移量進(jìn)行比較。如果它更大,則scrollView向右滾動(dòng)。如果它小于那么scrollView向左滾動(dòng):
// somewhere in the private class extension@property (nonatomic, assign) CGFloat lastContentOffset;// somewhere in the class implementation- (void)scrollViewDidScroll:(UIScrollView *)scrollView { ScrollDirection scrollDirection; if (self.lastContentOffset > scrollView.contentOffset.x) { scrollDirection = ScrollDirectionRight; } else if (self.lastContentOffset < scrollView.contentOffset.x) { scrollDirection = ScrollDirectionLeft; } self.lastContentOffset = scrollView.contentOffset.x; // do whatever you need to with scrollDirection here. }
我正在使用以下枚舉來(lái)定義方向。將第一個(gè)值設(shè)置為ScrollDirectionNone具有額外的好處,即在初始化變量時(shí)將該方向設(shè)置為默認(rèn)值:
typedef NS_ENUM(NSInteger, ScrollDirection) { ScrollDirectionNone, ScrollDirectionRight, ScrollDirectionLeft, ScrollDirectionUp, ScrollDirectionDown, ScrollDirectionCrazy,};

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
...我想知道用戶滾動(dòng)的方向(左,右)。
在這種情況下,在iOS 5及更高版本上,使用它UIScrollViewDelegate
來(lái)確定用戶平移手勢(shì)的方向:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x > 0) { // handle dragging to the right } else { // handle dragging to the left }}

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用scrollViewDidScroll:
是查找當(dāng)前方向的好方法。
如果您想在用戶完成滾動(dòng)后知道方向,請(qǐng)使用以下命令:
@property (nonatomic) CGFloat lastContentOffset;- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { self.lastContentOffset = scrollView.contentOffset.x;}- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { if (self.lastContentOffset < scrollView.contentOffset.x) { // moved right } else if (self.lastContentOffset > scrollView.contentOffset.x) { // moved left } else { // didn't move }}
- 3 回答
- 0 關(guān)注
- 798 瀏覽
添加回答
舉報(bào)