我想从视图控制器转到UITabBarController中的特定选项卡

ulr*_*ert 4 xcode tabbarcontroller

首先,让我说我是一个绝对的初学者,所以请原谅我,如果这是一个愚蠢的问题要问.我只想补充一点,我花了几个小时/几天试图弄清楚如何解决这个问题 - 包括对stackoverflow的广泛搜索(也许答案在某处,我现在不知道究竟要搜索什么:) .

但是,让我们继续:我对Xcode故事板项目有一个小问题.基本上我的项目看起来像这样:

导航控制器 - >查看控制器0 - >标签栏控制器 - <查看控制器1,视图控制器2,视图控制器3.

当用户在视图控制器0中按下"按钮#2"时,我希望他/她直接跳到"查看控制器2".

这有可能吗,如果是的话,应该使用什么代码,并且我应该把它放在哪里.

希望有人在那里帮助新手:)

此致,Ulrik

Max*_*hev 6

对的,这是可能的.您可以显示任何其他视图控制器.你应该简单地从加SEGUE button #2View Controller 2.(我假设您在单个故事板中拥有所有控制器)

更新:上面的解决方案将显示View Controller 2自己没有标签栏控制器.

没有看到实际的代码很难详细说明.有关详细信息,请参阅以下文档:

也许你会提出更具体的问题.

更新 如果要在标签栏控制器中预选所需的视图控制器,可以使用以下代码草图.在这里,您可以以编程方式启动segue并在prepareForSegue:sender:方法内部执行所需的预初始化.

static NSString * const kShowTabSegueID = @"ShowTab";

@interface ViewController ()

- (IBAction)buttonOnePressed;
- (IBAction)buttonTwoPressed;
- (IBAction)buttonThreePressed;

@end

@implementation ViewController

- (IBAction)buttonOnePressed
{
    [self performSegueWithIdentifier:kShowTabSegueID
                              sender:@0];
}

- (IBAction)buttonTwoPressed
{
    [self performSegueWithIdentifier:kShowTabSegueID
                              sender:@1];
}

- (IBAction)buttonThreePressed
{
    [self performSegueWithIdentifier:kShowTabSegueID
                              sender:@2];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue
                 sender:(id)sender
{
    if ([segue.identifier isEqual:kShowTabSegueID]) {
        NSNumber *indexToShow = sender;
        UITabBarController *tabBar = segue.destinationViewController;
        [tabBar setSelectedIndex:indexToShow.unsignedIntegerValue];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)


sta*_*tan 5

因此,如果我理解正确,您在选项卡栏控制器外部有一个视图控制器,并且您想从该(外部)视图控制器导航到选项卡栏控制器中的第二个选项卡,如果这是问题所在,那么这是我的解决方案,我希望它帮助别人,因为我自己花了一些时间在这个问题上。

首先使用模态转场将(外部)Viewcontroller 0 连接到情节提要中的选项卡栏控制器,并为其指定标识符 -“showTabBar”(而不是作为选项卡之一只是模态转场)。

然后:在 Viewcontroller 0 中声明:

var tabBarIndex: Int?

//function that will trigger the **MODAL** segue
private func loadTabBarController(atIndex: Int){
     self.tabBarIndex = atIndex
     self.performSegue(withIdentifier: "showTabBar", sender: self)
}

//in here you set the index of the destination tab and you are done
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

     if segue.identifier == "showTabBar" {   
         let tabbarController = segue.destination as! UITabBarController
         tabbarController.selectedIndex = self.tabBarIndex!       
     }         
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样导航到 ViewController 2(不要忘记它的索引是 0):

self.loadTabBarController(atIndex: 1)
Run Code Online (Sandbox Code Playgroud)

这是经过测试的,截至我使用 Swift 3.0.2 / Xcode 8.2.1 发布此答案的那天为止