如何在不使用标签栏控制器的情况下在故事板之间切换

How to switch between storyboards without using tab bar controller

我有 3 个 Storyboard(Main、First 和 Second),Storyboard Main 在其左上角的 View 中包含两个按钮(按钮:First 和 button:second),如果不使用 Tab Bar 控制器,我怎么能在主故事板中切换 First 和 Second,同时始终保持两个按钮可见?我已经尝试使用故事板参考,但是在选择其中一个按钮中,它只是在选定的故事板中,但由于需要从主故事板中的视图容器中看到按钮,因此容器视图似乎是一个选项,但不确定如何在该视图容器中的故事板之间切换,同时保持按钮可见。

请帮忙。谢谢

您不必在 Interface Builder 中使用 Storyboard Reference。您以编程方式创建引用,无论如何我发现它更简单、更容易理解。

界面生成器

确保通过检查 "Is Initial View Controller" 将 FirstViewControllerSecondViewController 设置为各自故事板的初始控制器。

代码

class MainViewController: UIViewController {
    @IBOutlet weak var contentView: UIView!

    // Initialize the first view controller of storyboard
    let firstViewController: FirstViewController = {
        let storyboard = UIStoryboard(name: "First", bundle: nil)
        return storyboard.instantiateInitialViewController() as! FirstViewController
    }()

    // Initialize the second view controller of storyboard
    let secondViewController: SecondViewController = {
        let storyboard = UIStoryboard(name: "Second", bundle: nil)
        return storyboard.instantiateInitialViewController() as! SecondViewController
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        show(childViewController: firstViewController)
    }

    @IBAction func showFirstVC(_ sender: Any) {
        // Don't show the first view controller again if it's already visible
        guard firstViewController.parent != self else { return }
        removeAllChildViewControllers()
        show(childViewController: firstViewController)
    }

    @IBAction func showSecondVC(_ sender: Any) {
        // Don't show the second view controller again if it's already visible
        guard secondViewController.parent != self else { return }
        removeAllChildViewControllers()
        show(childViewController: secondViewController)
    }

    // MARK: - Helper methods
    // Show a view controller in the `contentView`
    func show(childViewController vc: UIViewController) {
        self.addChildViewController(vc)
        self.contentView.addSubview(vc.view)
        vc.didMove(toParentViewController: self)
    }

    // Remove a view controller from the `contentView`
    func remove(childViewController vc: UIViewController) {
        vc.willMove(toParentViewController: nil)
        vc.removeFromParentViewController()
        vc.view.removeFromSuperview()
    }

    // Remove all child view controllers
    func removeAllChildViewControllers() {
        for childVC in self.childViewControllers {
            remove(childViewController: childVC)
        }
    }
}