如何在不使用标签栏控制器的情况下在情节提要之间切换

时间:2018-09-01 14:51:52

标签: swift xcode tvos

我有3个情节提要板(Main,First和Second),Storyboard Main的左上角视图中包含两个按钮(按钮:First和Button:Second),而没有使用Tab Bar控制器如何在两个之间切换从主故事板上的第一和第二同时保持两个按钮始终可见?我尝试使用情节提要参考,但是当选择其中一个按钮时,它只能插入到选定的情节提要中,这是行不通的,因为需要从主情节提要的视图容器中看到按钮,容器视图似乎是一个选项,但不确定如何在该视图容器中的情节提要之间切换,同时保持按钮可见。

请帮助。谢谢 enter image description here

1 个答案:

答案 0 :(得分:1)

您不必在Interface Builder中使用情节提要参考。您可以通过编程方式创建引用,但无论如何,我发现这些引用都更容易理解。

界面生成器

通过选中“是初始视图控制器”,确保将FirstViewControllerSecondViewController设置为其各自的情节提要的初始控制器。

Interface Builder Setup

代码

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)
        }
    }
}
相关问题