18

Мне нужно определить направление моего жестового удара, и у меня проблемы с ним. жест работает, но я не знаю, как определить направление. ...как определить направление движения пальцем?

swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe:)]; 
[swipeGesture setNumberOfTouchesRequired:1]; 
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp]; 
[appView addGestureRecognizer:swipeGesture]; 

-(void)detectSwipe:(UISwipeGestureRecognizer *)recognizer { 
switch (recognizer.direction) { 
    case UISwipeGestureRecognizerDirectionUp: 
     NSLog(@"smth1"); 
     break; 


    case UISwipeGestureRecognizerDirectionDown: 
     NSLog(@"smth2"); 
    default: 
     break; 
} 
} 

это не работает:/

+0

Уточнитните Имеет ли журнал неправильное значение? Разве это не журнал ничего? Является ли detectSwipe не вызываемым? – sosborn

+0

'default' case вызывается, когда я сажусь вверх или вниз. –

+0

Поскольку это всего лишь переименование - вы пытались использовать и регистрировать значение распознавателя: http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UISwipeGestureRecognizer_Class/Reference/Reference.html – bryanmac

ответ

20

Свойство direction только определяет разрешено направления, которые признаны в качестве пойла, а не направление конкретного взмаха фактической.

Проще всего было бы использовать два отдельных распознавателя жестов. Вы также можете проверить местоположение касания, когда начинается жест, и когда он заканчивается методом locationInView:. Решение

+0

'CGPoint start = [swipeGesture locationInView: appView];' я использую это, и эта функция дает мне начальную точку салфетки, но как я обнаруживаю, когда салфетки закончены? единственный способ - использовать 'touchhesBegan' и' touchesEnded'? –

+1

Я не уверен, что это действительно возможно (вам, вероятно, лучше с двумя распознавателями). Проверьте «состояние» распознавателя жестов в своем действии. Для большинства распознавателей жестов он переходит из 'UIGestureRecognizerStateBegan' в' UIGestureRecognizerStateEnded', но может быть, что тип распознавателя жестов не делает этого, я его не пробовал. – omz

+1

решена. Я использую 'touchhesBegan' и' touchesEnded'. –

11

EXTENDING ОМЗ:

self.myView мнение я хочу поставить жест распознаватель на. Код ниже не проверен, я думаю, было бы лучше сохранить распознаватели как property s и добавить их в файл viewDidLoad() или xib. self - UIViewController.

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedLeft:)]; 
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft ]; 
[self.view addGestureRecognizer:swipeLeft]; 

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedRight:)]; 
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight ]; 
[self.view addGestureRecognizer:swipeRight]; 

Добавьте эти два метода к вашему UIViewController и добавить необходимые действия:

- (IBAction)swipedRight:(UISwipeGestureRecognizer *)recognizer 
{ 
    NSLog(@"swiped right"); 
} 

- (IBAction)swipedLeft:(UISwipeGestureRecognizer *)recognizer 
{ 
    NSLog(@"swiped left"); 
} 
47

Вот пример одного из моих проектов: «он не работает»

// ... 

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; 
    [self.view addGestureRecognizer:swipeLeft]; 

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight; 
    [self.view addGestureRecognizer:swipeRight]; 

    UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 
    swipeUp.direction = UISwipeGestureRecognizerDirectionUp; 
    [self.view addGestureRecognizer:swipeUp]; 

    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 
    swipeDown.direction = UISwipeGestureRecognizerDirectionDown; 
    [self.view addGestureRecognizer:swipeDown]; 

    // ... 

- (void)didSwipe:(UISwipeGestureRecognizer*)swipe{ 

    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) { 
     NSLog(@"Swipe Left"); 
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionRight) { 
     NSLog(@"Swipe Right"); 
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionUp) { 
     NSLog(@"Swipe Up"); 
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionDown) { 
     NSLog(@"Swipe Down"); 
    } 
} 
+0

Это идеальное решение для меня –

+0

Думаю, вам не нужно добавлять 4 распознавателя жестов, просто добавьте один, а в методе didSwipe проверьте направление движения отправителя, которое должно это сделать –

Смежные вопросы