您不必在Interface Builder中使用Storyboard Reference。您可以通过编程方式创建引用,但无论如何,我发现这些引用都更容易理解。
请确保您设置FirstViewController
并SecondViewController
通过检查各自的故事板的初始控制器“是初始视图控制器”。
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)
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句