我有 3 个 Storyboard(Main、First 和 Second),Storyboard Main 在其左上角的 View 中包含两个按钮(按钮:First 和 button:second),如果不使用 Tab Bar Controller ,我该如何切换First 和 Second 来自主 Storyboard,同时始终保持两个按钮可见?我已经尝试使用 Storyboard引用,但是在选择其中一个按钮时,它只是在选定的 Storyboard中划分,但由于需要从主 Storyboard中的 View 容器中看到按钮,因此容器 View 似乎是一个选项,但不确定如何在该 View 容器中的 Storyboard之间切换,同时保持按钮可见。
最佳答案
您不必在 Interface Builder 中使用 Storyboard Reference。您以编程方式创建引用,无论如何我发现它更简单、更容易理解。
界面生成器
确保通过选中“Is Initial View Controller”将 FirstViewController
和 SecondViewController
设置为其各自 Storyboard的初始 Controller 。
代码
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)
}
}
}
关于swift - 如何在不使用标签栏 Controller 的情况下在 Storyboard之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129255/