UITabBarController 在选项卡索引 1 处存在 VC

UITabBarController present VC at tab index 1

我需要显示链接到 UITabBarController 的第二个选项卡(索引:1)的 VC。不使用故事板 segues。

使用 segues 它正在工作。代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let tabVC = segue.destination as? UITabBarController 
    tabVC.selectedIndex = 1
}

在不使用 segues 的情况下,我的代码看起来像(见下文)。尽管我将 selectedIndex 设置为 1(第二个选项卡),但在显示选项卡 VC 时会显示第一个(索引:0)选项卡。有什么建议可以解决这个问题吗?谢谢

func presentTab1(_ sender: Any) {

    let tabVC =  MainTabBar() 
    tabVC.selectedIndex = 1

    present(tabVC, animated: true, completion: nil)
}

我建议将选定的索引传递给构造函数并在 ViewDidLoad 中设置 SelectedIndex。

有两种方法,您可以使用其中任何一种

1.) 如果你有 NavigationController 然后在你的函数中尝试下面的代码行。

func presentTab1(_ sender: Any) {
    let targetVC = self.storyboard?.instantiateViewController(withIdentifier: "NavigateionControllerIdentifier") as! UINavigationController
    self.present(targetVC, animated: true)
}

2.) 或者,如果您想直接导航至 ViewConteroller,则

func presentTab1(_ sender: Any) {
    let targetVC = (self.storyboard?.instantiateViewController(withIdentifier: "viewControllerIdentifier"))!
    self.present(targetVC, animated: true)
}

第 1 步:

为您要转到的视图控制器命名。 Select 那个视图控制器并从这里给出了那个 VC

第 2 步:

使用以下代码导航至 VC:

let targetVC = 
(self.storyboard?.instantiateViewController(withIdentifier: "someVC"))!
self.present(targetVC, animated: true)

如果你有导航控制器的话。

let targetVC = 
self.storyboard?.instantiateViewController(withIdentifier: "NavigationControllerId") as! UINavigationController
self.present(targetVC, animated: true)

我遇到了同样的问题,你可以这样做:

func presentTab1(_ sender: Any) {
    self.tabBarController?.selectedIndex = 1
    _ = self.navigationController?.popToRootViewController(animated: true)
}

对我来说很好用! 您只需要知道您要访问哪个索引即可。