Вопрос

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

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

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

Это было полезно?

Решение

А direction свойство только определяет допустимый направления, которые признаются как провисания, а не действительный направление конкретного удара.

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

Другие советы

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

    // ...

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

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

self.myView Являюсь ли я, я хочу включить распознавание жестов. Приведенный ниже код не протестирован, я думаю, было бы лучше сохранить распознаватели как propertys и добавить их внутрь 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");
} 

Направление жеста проведите с помощью 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")
        }
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top