如何在Swift上的两个子视图控制器之间切换?

Fra*_*ero 9 uinavigationcontroller ios uistoryboardsegue uicontainerview swift

我试图View Controllers在一个特定的两个孩子之间切换Container View.我有一个Navigation Controller菜单(Table View用于制作菜单的不同选项).

每次我点击菜单的一个选项,我想改变的孩子Container View,但我得到上面的孩子Navigation barTable View(未示出它们,但它们是新的子视图控制器下).

我的Main.storyboard的方案是这样的:

Navigation Controller --> View Controller (With 2 Container View, 1 for Table View
                                           and the other to set master View Controller)
                                         |
                                         |
                               ------------------------
                               |                      |
                          View Controller        Table View
                            (id: master)

                   View Controller (id: Home)   View Controller (id: screen2)
Run Code Online (Sandbox Code Playgroud)

我在tableView函数上有以下代码(我在其中检测单击菜单的选项时)来更改容器视图的子视图控制器:

let currentController = self.navigationController?.visibleViewController //container

var oldChild = (currentController?.childViewControllers.last!)! as UIViewController //master
let newChild = (storyboard?.instantiateViewControllerWithIdentifier("Home"))! as UIViewController //Home

if (oldChild != newChild){
    if currentController.childViewControllers.last != nil{
        oldChild.willMoveToParentViewController(nil)
        currentController.navigationController?.navigationBar.willRemoveSubview(oldChild.view)
        //oldChild.view.removeFromSuperview()
        oldChild.removeFromParentViewController()
    }

    currentController.addChildViewController(newChild)
    currentController.view.addSubview(newChild.view)
    newChild.didMoveToParentViewController(currentController) 
}
Run Code Online (Sandbox Code Playgroud)

这段代码工作得很好.问题是新的子视图控制器显示在导航栏和表视图(菜单)上方.所以它占据了整个屏幕,而不是适合容器视图.

我应该在代码中添加更多内容还是以错误的方式使用我的代码?我已经搜索了很多关于它的信息,但大多数解决方案都是客观的,或者对我不起作用.

编辑:搜索了很多小时后,我怀疑它是与嵌入式segue相关的东西,它将根View ControllermasterView Controller 连接起来,但是我无法将新的子项嵌入到Container View.我正在尝试的代码是:

currentController.performSegueWithIdentifier("EmbedSegue", sender: newChild)
Run Code Online (Sandbox Code Playgroud)

要么

currentController.presentViewController(newChild, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

但他们都没有嵌入segue.只需newChild在全屏显示即可.

提前致谢!

小智 4

您应该拥有 ContainerView 的 IBOutlet 并将 Subview 添加到此 IBOutlet

currentController.containerView.addSubview(newChild.view)
Run Code Online (Sandbox Code Playgroud)

或者

currentController.addSubview(childView.view, toView: self.containerView)
Run Code Online (Sandbox Code Playgroud)