Jongers
Jongers

Reputation: 691

Objective-C switch tabs using swipe

I followed a code that switches tabs when the user swipes left / right on the screen. The problem is that when I switch to the other tabs, the tab bar disappears.

I tried pushing a navigationController but it throws an error saying that it is not supported.

Here is the code:

- (void)viewDidLoad {
    [super viewDidLoad];
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];
    swipeLeft.delegate = self;

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

-(void) swipeRight:(UISwipeGestureRecognizer *) recognizer {
    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight){
        //NSLog(@"swipe right");
        NSString * storyboardName = @"Main";
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
        UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"RecentsController"];
        [self presentViewController:vc animated:YES completion:nil];

    }
}

-(void) swipeLeft:(UISwipeGestureRecognizer *) recognizer {
    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight)
        NSLog(@"Swipe left");
    NSString * storyboardName = @"Main";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"SettingsController"];
    [self presentModalViewController:vc animated:YES];
}

Upvotes: 2

Views: 724

Answers (1)

Rahul
Rahul

Reputation: 5834

You are doing it in a wrong way. To switch you Tab Bar via code you don't have to push a new ViewController it will replace your existing one.

To do so you can use one of the following methods:

self.tabBarController.selectedIndex = i;

or

[self.tabBarController setSelectedIndex:i];

**** Where i is the index of your ViewController you want to show.

Upvotes: 2

Related Questions