2013-04-02 73 views
2

我需要從UIScrollView中獲取觸摸位置。但是,當我創建一個子類爲我的滾動視圖:在UiScrollView上檢測觸摸位置

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    NSArray *touchesArray = [touches allObjects]; 
    UITouch *touch = (UITouch *)[touchesArray objectAtIndex:0]; 
    CGPoint point = [touch locationInView:self]; 
    self.position = point;} 

功能touchesBegan並不總是叫。 如果我快速刷卡,touchesBegan永遠不會被調用,但scrollViewDidScroll會直接調用。

我不能使用UIGesture (UITapGestureRecognizer, ...),因爲用戶不點擊或滑動。

是否有其他的方法來得到的UIScrollView的位置?

編輯:

感謝ThXou:https://stackoverflow.com/a/15763450/1752843

UIScrollView的子類:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ 
    self.position = point; 
    return self; 
} 

回答

2

我看到an answer所以我認爲它可以解決你的問題。看起來SDK不再將觸摸處理方法傳遞給UIScrollView子類。因此,您應該執行hitTest:將觸摸傳遞給您的子類。

查看答案獲取更多信息。

+0

Thx!我的代碼:' - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { self.position = point; 迴歸自我; }' – VivienCormier

6

爲了檢測內滾動視圖觸摸位置,試試這個代碼

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)]; 
[scrollView addGestureRecognizer:singleTap]; 

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture 
{ 
    CGPoint touchPoint=[gesture locationInView:scrollView]; 
} 
+0

但是當我滾動視圖滾動永遠不會被調用的函數「的touchesBegan」或「touchesMoved」。我希望在使用我的滾動視圖時獲得聯繫。 – VivienCormier

+0

即使「touchesBegan」是空的,她也不會被調用。 – VivienCormier

+0

不好意思嘗試上面的代碼。其他方法是俞需要調用子類。欲知詳情,請查看此鏈接http://iosdevelopertips.com/user-interface/detect-single-tap-in-uiscrollview.html – iVenky

0

你可以選擇使用scrollview.panGestureRecognizerlocationInView方法來獲取觸摸的座標在您的視圖。這可以根據您的要求在scrollView的委託方法中進行。

0
scrollView.delaysContentTouches = NO; 

這將使touchesBegan和其他觸摸事件將在scrollViewDidScroll之前觸發。

的則hitTest是一個黑客並且不應當被優選的解決方案。