Search code examples
objective-ciphonexcodeuser-interfaceuiswipegesturerecognizer

How to swipe down to dismiss current page in Xcode


So I wrote this line of code to dismiss the current tutorial page and let the user use the app but when you swipe down , the tutorial page will disappear for 1 second and it will come back.

So I wrote these lines of code in the tutorial's view controller.m

-(void)swipeHappened:(UISwipeGestureRecognizer *)swipe
{
    NSLog(@"Swipe Occurred");

    switch (swipe.direction) {
        case UISwipeGestureRecognizerDirectionRight:
            NSLog(@"Right");
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        case UISwipeGestureRecognizerDirectionLeft:
            NSLog(@"Left");
            break;
        case UISwipeGestureRecognizerDirectionUp:
            NSLog(@"Up");
            break;
        case UISwipeGestureRecognizerDirectionDown:
            NSLog(@"Down");
            break;
    }

}

and these in the mainviewcontroller.m

 -(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];


    TutorialViewController *tutorialViewController=[[TutorialViewController alloc] initWithNibName:@"TutorialViewController" bundle:nil];
    [self presentViewController:tutorialViewController animated:YES completion:NULL];


    //I  HAVE A PROBLEM HERE( there's no error that appears in Xcode but it is not the result I expected 

}

Solution

  • A couple of things could be the issue. First, is MainViewController the parent of TutorialViewController? If so, then when you dismiss the tutorial and your main controller calls viewDidAppear, you're popping the tutorial right back in place.

    If this is the issue, you need to remove the code in viewDidAppear that presents the tutorial. Maybe present it from the app delegate as your first controller instead?

    Also, the direction property of UISwipeGestureRecognizer is used for setting direction only, so your switch statement probably won't work the way you expect it to. Try creating a direction-specific recognizer like this:

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

    If you need to react differently to swipes in each direction you should create four separate gesture recognizers for each.