Objective-C使用滑动切换选项卡

时间:2015-11-04 05:52:08

标签: objective-c swipe uitabbar

我跟着一个代码,当用户在屏幕上左/右滑动时切换标签。问题是,当我切换到其他选项卡时,标签栏消失。

我尝试过推送一个navigationController,但它会抛出一个错误,说它不受支持。

以下是代码:

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

1 个答案:

答案 0 :(得分:2)

你这样做是错误的。要通过code切换标签栏,您无需推送新ViewController它将替换现有标签栏。

为此,您可以使用以下方法之一:

self.tabBarController.selectedIndex = i;

[self.tabBarController setSelectedIndex:i];

**** i是您想要展示的index的{​​{1}}。