我举了一个例子来说明我认为你正在努力实现的目标。点击标签栏按钮会在黄色视图中显示其各自的视图控制器。
首先在Interface Builder中排列三个视图控制器,如上图。将一个普通的UIView(不是容器视图)拖到主视图控制器上并定位它(根据需要使用约束)。在下面添加标签栏(设置其代表)和标签,如图所示。
然后按住 Control 并拖动以创建从主视图控制器到每个子视图控制器的 segue。当弹出窗口选择 segue 类型时,选择自定义:
然后单击每个 segue 连接并在 Attributes Inspector 中为每个连接指定一个标识符(例如 first 和 second),并将它们的类设置为 MySegue(我们将很快创建一个自定义 segue):
假设主视图控制器设置为 ViewController 类,请将 ViewController.swift 替换为以下内容:
class MySegue: UIStoryboardSegue {
override func perform() {
// Leave empty (we override prepareForSegue)
}
}
class ViewController: UIViewController, UITabBarDelegate {
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Load the first screen by default.
performSegue(withIdentifier: "first", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue is MySegue {
// This is an example of how to use the UIViewController containment APIs.
// If we're starting, there is not yet a child view controller added, so
// just add it.
if childViewControllers.count == 0 {
self.addChildViewController(segue.destination)
segue.destination.view.frame = containerView.bounds
self.containerView.addSubview(segue.destination.view)
segue.destination.didMove(toParentViewController: self)
// If there is already a child, swap it with the segue's destination view controller.
} else {
let oldViewController = self.childViewControllers[0]
segue.destination.view.frame = oldViewController.view.frame
oldViewController.willMove(toParentViewController: nil)
self.addChildViewController(segue.destination)
self.transition(from: oldViewController, to: segue.destination, duration: 0, options: .transitionCrossDissolve, animations: nil) { completed in
oldViewController.removeFromParentViewController()
segue.destination.didMove(toParentViewController: self)
}
}
}
}
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let index = tabBar.items?.index(of: item) else { return }
switch index {
case 0:
performSegue(withIdentifier: "first", sender: nil)
case 1:
performSegue(withIdentifier: "second", sender: nil)
default:
break
}
}
}
现在将containerView 的 IBOutlet 连接到主视图控制器的黄色视图。
编译并观察点击标签栏按钮如何在黄色视图内的两个视图控制器之间切换,保持上面的共享标签。
这是 UIViewController 包含 API 的示例。