10

我有一個使用UIPanGestureRecognizer移動的圖像類型對象,並且當對象到達特定幀時我需要停止識別UIPanGestureRecognizer。如何當對象移動到特定幀時停止UIPanGestureRecognizer

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)]; 
    [panRecognizer setMinimumNumberOfTouches:1]; 
    [panRecognizer setMaximumNumberOfTouches:1]; 
    [panRecognizer setDelegate:self]; 
    [templatePhotoPlaceholderView addGestureRecognizer:panRecognizer]; 

-(void)move:(UIPanGestureRecognizer *)gestureRecognizer 
{ 
    CGPoint translatedPoint = [gestureRecognizer translationInView:templatePhotoPlaceholderView]; 

    if([gestureRecognizer state] == UIGestureRecognizerStateBegan) { 
     _firstX = [imageview center].x; 
     _firstY = [imageview center].y; 
    } 



    translatedPoint = CGPointMake(_firstX+translatedPoint.x, _firstY+translatedPoint.y); 
    //NSLog(@" Move center point :%@", NSStringFromCGPoint(translatedPoint)); 

    [imageview setCenter:translatedPoint]; 

} 

我該怎麼做?

回答

21

UIGestureRecognizers有一個啓用的屬性。文檔:

禁用手勢識別器,因此它沒有接收到觸摸。 默認值爲YES。如果在手勢識別器當前正在識別手勢時將此屬性更改爲NO,則手勢 識別器將轉換爲取消狀態。

編輯:

剛剛啓用的屬性設置爲NO。

gestureRecognizer.enabled = NO; 
+2

嗨jbat。你能給我一些線代碼的例子嗎?用於停止UIGestureRecognizers – user905582

8

當你需要從識別手勢阻止你UIPanGestureRecognizer,你只要把這個代碼行(如jbat100說)在-(void)move:(UIPanGestureRecognizer *)gestureRecognizer

gestureRecognizer.enabled = NO; 

此行您gestureRecognizer狀態設置爲"UIGestureRecognizerStateCancelled"

然後只需添加幾條線到您的-(void)move:(UIPanGestureRecognizer *)gestureRecognizer功能:

if ([gestureRecognizer state] == UIGestureRecognizerStateCancelled) { 
    gestureRecognizer.enabled = YES; 
} 

,你就可以用你的手勢識別

編輯工作

這裏的代碼片段:

- (void)move:(UIPanGestureRecognizer *)gestureRecognizer { 
    BOOL cancelPanGesture = YES; 
    if (cancelPanGesture) { 
     /* 
     After this line gesture recognizer will be disabled, state will be UIGestureRecognizerStateCancelled 
     and this method (move:) will fire one more time. 
     */ 
     gestureRecognizer.enabled = NO; 
    } 
    if (gestureRecognizer.state == UIGestureRecognizerStateCancelled) { 
     gestureRecognizer.enabled = YES; 
    } 
} 
+1

答案沒有意義,應該寫入'gestureRecognizer.enabled = YES;'的位置。如果你能詳細說明會更有意義。 –

+0

@ rohan-patel謝謝你的評論,我已經更新了我的答案。 – derpoliuk

+1

我喜歡這個。它保持識別器的狀態封裝在該函數中,而不是在代碼中放置愚蠢的'shouldCancelPan'實例變量。 –

3

設置pangesture.delegate =自我,實現委託方法

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer 
{ 
    //return NO when you reach the frame 
} 
相關問題