使用TabBarViewController呈现NavigationController无法以编程方式选择索引

时间:2019-07-05 09:53:07

标签: ios swift iphone uinavigationcontroller swift5

我正在尝试显示NavigationController并在完成块中选择第二个选项卡。我的代码是:

public class Client {
    private UserClass User { get; };

    public Client(UserClass user)
    {
        User = user;
    }

    public void Verify(string serveraddress, string domain)
    {
        try 
        {
            var connection = new LdapConnection();
            connection.Connect(serveraddress, 389);
            // try to connect, if success go through this step and return true
            return true;
        }
        catch
        {
            return false;
        }
    }

    public string GetEmail()
    {
        // Connect again
        // Here, it is redundant when I have to connect again to retrieve the information
    }
}

第二次尝试:

let chatViewController = UITabBarController()
let navigationController = UINavigationController(rootViewController: chatViewController)

present(navigationController, animated: true, completion: {
    self.visibleViewController = navigationController
    self.visibleViewController?.tabBarController?.selectedIndex = 1
})

在两种情况下,tabBarController均为nil。如何切换到其他标签?

3 个答案:

答案 0 :(得分:3)

您正尝试访问UITabBarController中的UINavigationController,但是您需要从UINavigationController访问第一个控制器,并且需要从此处选择UITabBar这样:

func showTabBarControllerr() {
    let chatViewController = UITabBarController()
    //Note: Make sure you have already added the Controllers in Tabbarcontroller
    chatViewController.viewControllers = [DemoOne(), DemoTwo()]
    let navigationController = UINavigationController(rootViewController: chatViewController)
    present(navigationController, animated: true, completion: {
        if let tabBarController = navigationController.viewControllers.first as? UITabBarController {
            tabBarController.selectedIndex = 1
        }
    })
}

让我知道这是否有帮助!

答案 1 :(得分:1)

代替呼叫

present(navigationController, animated: true, completion: { })

viewDidLoad中,尝试在viewWillAppearviewDidAppear

中调用它

答案 2 :(得分:0)

尝试一下(快速5):

  1. 在情节提要中为UITabBarController设置一个标识符,类似于MainTabBar

  2. 在函数或IBAction中,使用以下代码:

    让tbc = storyboard?.instantiateViewController(withIdentifier:“ MainTabBar”)为! UITabBarController

    tbc.selectedIndex = 1 //这是您的控制器的索引

    present(待定,动画:false,完成:nil)

相关问题