2011-12-03 23 views
2

好的,我遇到了一個非常奇怪的問題(對我來說)。在我看來,我有一個150x150的按鈕,並且我已經爲該按鈕添加了一個UILongPressGestureRecognizer,因爲我需要在按下按鈕時按下該按鈕。我的代碼,這樣做看起來是這樣的:當按鈕在普通視圖試圖獲得觸點,返回NaN

-(CGPoint)detectedTouch:(UILongPressGestureRecognizer *)sender { 

    CGPoint touchPoint = [sender locationInView:button]; 
    return touchPoint; 
} 


-(void)myAction { 

    CGPoint touchPoint = [self detectedTouch:myGestureRecognizer]; 
    NSLog(@"touchPoint = %f, %f", touchPoint.x, touchPoint.y); 

    //do stuff 
} 

現在一切都工作得很好。但是,當按鈕在scrollView上時,它只有在你按下約一秒鐘時纔有效。如果你釋放得太快,日誌會給我這個:

touchPoint = nan, nan 

任何幫助解決這個問題將不勝感激!

回答

2

UIGestureRecognizer在他們的生命週期中有不同的狀態,例如可能的,被識別的,失敗的,結束的,取消的。我會試着在你的識別器方法裏面加上一個switch語句,看看發生了什麼,以便更好地縮小問題的範圍。這將是這個樣子:

switch (sender.state){ 
    case UIGestureRecognizerStatePossible: 
     NSLog(@"possible"); 
     break; 
    case UIGestureRecognizerStateFailed: 
     NSLog(@"Failed!"); 
     break; 
    ... All Cases wanted 
    default: 
     break; 
} 

我不知道的內部細節,但也許如果失敗/取消它不會在視圖中拾取的位置。

這是關於子類化手勢識別器和可能發生的狀態的文檔。

http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html

+0

好的,謝謝你,但不知何故我的問題與scrollView有關。獲取觸點的要點是以不同的方式製作按鈕的動畫,具體取決於您觸摸的位置。爲了測試,我刪除了檢查觸摸位置的部分,並在按下按鈕時使按鈕向下移動並在不再按下時將其移回原始位置。在常規視圖中,它按預期工作,但在scrollView上它只能在延遲之後(如上所述)工作,並且動畫不流暢。有任何想法嗎? – kopproduction

0

我試圖重現你的問題,但沒有成功。起初,我認爲手勢識別器可能會干擾scrollView滾動手勢識別器,但似乎並非如此。這裏是我的代碼有:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongHold:)]; 
// [scrollView addGestureRecognizer:recognizer]; 
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 2000)]; 
    lbl.text = @"lorem ipsum......"; 
    lbl.numberOfLines = 0; 
    scrollView.contentSize = CGSizeMake(lbl.frame.size.width, lbl.frame.size.height); 
    [scrollView addSubview:lbl]; 
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btn.frame = CGRectMake(0, 0, 150, 150); 
    [btn addGestureRecognizer:recognizer]; 
    [scrollView addSubview:btn]; 

    v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
    v.backgroundColor = [UIColor yellowColor]; 
    v.hidden = YES; 
    [scrollView addSubview:v]; 
} 

- (void) handleLongHold:(UILongPressGestureRecognizer*) recognizer { 
    NSLog(@"long tap handled"); 
    v.hidden = NO; 
    v.center = [recognizer locationInView:btn]; 
} 

順便說一句,我無意中發現你的問題尋找一種方式來找到一個手勢識別選擇觸摸點 - locationInView方法幫助我,並希望這個代碼可以幫助你。