2014-07-05 178 views
7

我在我的應用程序中使用UIScrollView,並使用scrollviewDidScroll方法來移動不在滾動視圖內的其他視圖。只有當用戶實際上用手指移動滾動視圖而不是觸摸事件結束時,纔會出現此行爲。UiScrollview scrollviewDidScroll檢測用戶觸摸

目前我使用scrollview的dragging屬性來獲得此行爲,但它有一個問題:當用戶在滾動視圖上滑動並在其停止減速之前再次觸摸它,dragging屬性不正確,雖然用戶用手指拖動滾動視圖。

+0

查看tableView的'UIGestureRecognizerState',比如'yourTableView.panGestureRecognizer.state'。它將揭示用戶觸摸的狀態究竟是什麼。在'scrollViewDidScroll'中執行。 – n00bProgrammer

+1

完成。帶示例代碼 – n00bProgrammer

回答

19

UIScrollView有一個panGestureRecogniser屬性,該屬性跟蹤滾動視圖中的平移手勢。你可以跟蹤移動手勢的statescrollViewDidScroll確切地知道什麼狀態平移是英寸

雨燕4.0

func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    if scrollView.isEqual(yourScrollView) { 
     switch scrollView.panGestureRecognizer.state { 
      case .began: 
       // User began dragging 
       print("began") 
      case .changed: 
       // User is currently dragging the scroll view 
       print("changed") 
      case .possible: 
       // The scroll view scrolling but the user is no longer touching the scrollview (table is decelerating) 
       print("possible") 
      default: 
       break 
     } 
    } 
} 

Objective-C的

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { 

    if ([scrollView isEqual:yourScrollView]) { 

     switch (scrollView.panGestureRecognizer.state) { 

      case UIGestureRecognizerStateBegan: 

       // User began dragging 
       break; 

      case UIGestureRecognizerStateChanged: 

       // User is currently dragging the scroll view 
       break; 

      case UIGestureRecognizerStatePossible: 

       // The scroll view scrolling but the user is no longer touching the scrollview (table is decelerating) 
       break; 

      default: 
       break; 
     } 
    } 
} 
1

IMO更好的回答是使用UIScrollViewDelegate,有以下通知:

// called on start of dragging (may require some time and or distance to move) 
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView; 
// called on finger up if the user dragged. velocity is in points/millisecond. targetContentOffset may be changed to adjust where the scroll view comes to rest 
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0); 
// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards 
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate; 
+0

您還需要監聽「scrollViewDidScrollToTop」。 – kelin

+0

@kelin這與用戶touch有什麼關係? –

+0

當用戶雙擊狀態欄時會調用此事件。這導致表視圖滾動到頂部。閱讀'UIScrollViewDelegate'文檔。 – kelin