2013-06-27 44 views
10

我想在用戶開始拖動時檢測我的UIScrollView中的(初始)觸摸位置。我搜索了這個問題,很多人似乎都在爲這個問題而努力。現在,雖然我仍然無法理解Apple爲什麼不讓用戶在滾動視圖中訪問觸摸信息,但我不禁要自己找到解決方案。然而,我所有的嘗試都失敗了,所以我想問你。在UIScrollView上檢測觸摸位置?

這裏是我想會的工作:

我成立了一個UIPanGestureRecognizer像這樣在我的UIScrollView子類,並將其添加到它的手勢識別:

UIPanGestureRecognizer *tapDrag = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(touchedAndDragged:)]; 
tapDrag.cancelsTouchesInView = NO; 
tapDrag.delegate = self; 
[self addGestureRecognizer:tapDrag]; 

和相應的方法:

-(void)touchedAndDragged:(UIPanGestureRecognizer*)t{ 

    CGPoint loc = [t locationInView:self]; 
    //do something with location (that is exactly what I need) 
    //... 

    //Now DISABLE and forward touches to scroll view, so that it scrolls normally 
    t.enabled = NO; 
    /**** 
    ????? 
    *****/ 

} 

正如評論所示,我想禁用平移手勢後,我有點,然後禁用識別器(而仍然拖動!)並將觸摸「傳遞」到我的滾動視圖,以便用戶可以正常滾動。這是否可行?還有其他解決方案嗎?

回答

31

那麼UIScrollView已經有一個內置的平移手勢,你可以利用。用法與將滾動視圖的委託設置爲(使用scrollViewWillBeginDragging)並使用UIPanGestureRecognizer的-locationInView:來確定觸摸位置一樣簡單。

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 
{ 
    CGPoint location = [scrollView.panGestureRecognizer locationInView:scrollView]; 
    NSLog(@"%@",NSStringFromCGPoint(location)); 
} 
+0

是否有可能檢測出這個滾動是否在某個xx位置,然後scrollView滾動或觸摸將不會被觸發?假設我在滾動視圖中有兩個視圖,一個地圖和一個面板在地圖下方,我不希望滾動視圖在我觸摸地圖時觸發其代表,並且地圖應該觸及它 –

0

爲什麼不抓住-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event的起始位置,這將更加方便和高效。

+3

我完全意識到觸摸功能,事實上,我試圖實現它們,但它們根本不會被調用。 –

+0

未啓用用戶交互。但禁用它,它會。但是,那麼你將無法與其任何childobjects進行交互... – Philip