как определить направление жеста смахивания?

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

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;
}
}

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


person Tomasz Szulc    schedule 11.01.2012    source источник
comment
Пожалуйста, определите, что это не работает. В журнале указано неверное значение? Он ничего не регистрирует? ДетекторSwipe не вызывается?   -  person sosborn    schedule 11.01.2012
comment
default случай вызывается, когда я прокручиваю вверх или вниз.   -  person Tomasz Szulc    schedule 11.01.2012
comment
Поскольку это просто перечисление - пытались ли вы привести и зарегистрировать значение распознавателя: developer.apple.com/library/IOs/#documentation/UIKit/Reference/   -  person bryanmac    schedule 11.01.2012


Ответы (4)


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

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

person omz    schedule 11.01.2012
comment
CGPoint start = [swipeGesture locationInView:appView]; я использую это, и эта функция дает мне начальную точку смахивания, но как я могу определить, когда смахивание закончилось? единственный способ - использовать touchesBegan и touchesEnded? - person Tomasz Szulc; 11.01.2012
comment
Я не уверен, возможно ли это на самом деле (вам, вероятно, лучше с двумя распознавателями). Проверьте state распознавателя жестов в своем действии. Для большинства распознавателей жестов он переходит от UIGestureRecognizerStateBegan к UIGestureRecognizerStateEnded, но может случиться так, что тип распознавателя жестов не делает этого, я не пробовал. - person omz; 11.01.2012

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

    // ...

    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");
    }
}
person nemelianov    schedule 27.01.2014
comment
Я думаю, вам не нужно добавлять 4 распознавателя жестов, просто добавьте один и в методе didSwipe проверьте направление смахивания отправителя, это должно сделать это - person Sumit Kumar Saha; 16.01.2018

Расширение решения omz:

self.myView — это вид, на который я хочу поместить распознаватель жестов. Приведенный ниже код не тестировался, я думаю, было бы лучше сохранить распознаватели как property и добавить их в файл 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");
} 
person Yunus Nedim Mehel    schedule 29.05.2013

Определение направления жеста смахивания с помощью Swift 5

    override func viewDidLoad() {
    super.viewDidLoad()

         let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
         let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))

         leftSwipe.direction = .left
         rightSwipe.direction = .right

         view.addGestureRecognizer(leftSwipe)
         view.addGestureRecognizer(rightSwipe)
    }

    @objc func handleSwipes(_ sender:UISwipeGestureRecognizer) {

        if (sender.direction == .left) {
                print("Swipe Left")
        }

        if (sender.direction == .right) {
            print("Swipe Right")
        }
    }
person Raj Joshi    schedule 27.08.2019