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

问题描述 投票:1回答:1

我有3个故事板(Main,First和Second),Storyboard Main在其左上角的View中包含两个按钮(按钮:First,和按钮:second),不使用Tab Bar控制器如何在First和Second之间切换从主故事板,同时保持两个按钮可见?我已经尝试过使用Storyboard Reference,但是当选择其中一个按钮时,它只是进入选定的故事板并且不起作用,因为按钮需要在主故事板的视图容器中可见,容器视图似乎是一个选项但不确定如何在保持按钮可见的同时在该视图容器中的故事板之间切换。

请帮忙。谢谢你enter image description here

swift xcode tvos
1个回答
1
投票

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

Interface Builder

确保通过选中“是初始视图控制器”将FirstViewControllerSecondViewController设置为各自故事板的初始控制器。

Code

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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.