如果在 viewcontroller 中使用 UITabbar,如何设置 homeview 控制器

How to set homeview controller if use a UITabbar in a viewcontroller

我已将单独的 UITabbar 添加到 viewcontroller。制造了所有必要的出口。首页 viewcontroller 中有标签栏。我想要什么如果我点击第一个按钮,应该没有变化,但如果点击第二个标签栏项目,它应该显示第二个屏幕。

    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem){
        switch item.tag {

        case 1:
            if sampleOne == nil {

                var storyboard = UIStoryboard(name: "Main", bundle: nil)

                sampleOne = storyboard.instantiateViewController(withIdentifier: "s1") as! SampleOneViewController
            }
            self.view.insertSubview(sampleOne!.view!, belowSubview: self.sampleTabBar)

            break


        case 2:
            if sampleTwo == nil {

                var storyboard = UIStoryboard(name: "Main", bundle: nil)

                sampleTwo = storyboard.instantiateViewController(withIdentifier: "s2") as! SampleTwoViewController
            }
            self.view.insertSubview(sampleTwo!.view!, belowSubview: self.sampleTabBar)

            break

        default:

            break

        }

    But it loads Homeviewcontroller first then it shows the other viewcontroller. 
    Now how should i set the homeviewcontroller(which has uitabbar in it) as first viewcontroller. 

为了暗部的帮助?

根据文档,如果您想在保持 viewcontroller 不变的同时在不同视图之间切换,请使用 UITabBar。但是如果你想在不同的 viewcontroller 之间切换,UITabBarController 应该是首选方式。

你在使用UITabBar切换viewcontrollers时可能面临的问题是需要手动处理很多事情。例如。添加和删​​除您的 child viewcontrollers.

但如果您仍然坚持这样做,请在您的 viewcontroller 之间使用 parent child 关系。使您的 HomeViewController 成为 parent 视图。现在 viewDidLoad 假设默认选择第一项,添加 SampleOneViewController 如下:

        if let vc = self.storyboard?.instantiateViewController(withIdentifier: "s1") as? SampleOneViewController {
        self.addChildViewController(vc)
        self.view.insertSubview(vc, belowSubview: tabBar)
    }

现在在标签栏委托中,您需要先删除之前的 child viewcontroller,然后再添加索引选择的那个。

所以你的委托方法会变成这样:

func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem){
    switch item.tag {

// Remove the previous child viewcontrollers
    for vc in self.childViewControllers {
        vc.willMove(toParentViewController: nil)
        vc.view.removeFromSuperview()
        vc.removeFromParentViewController()
    }


    case 1:

    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "s1") as? SampleOneViewController {
        self.addChildViewController(vc)
        self.view.insertSubview(vc, belowSubview: self.view)
    }

        break


    case 2:
    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "s2") as? SampleTwoViewController {
        self.addChildViewController(vc)
        self.view.insertSubview(vc, belowSubview: self.view)
    }

        break

    default:

        break

    }

希望这对您有所帮助。