iOS Swift - 在容器视图中实现 SplitViewController

iOS Swift - implementation of SplitViewController inside a Container View

我正在学习本教程link

但是我从一开始就做了一个改变。

我添加了一个 ViewController(并使其成为初始视图控制器)并在其中添加了一个容器视图。

然后我在我的 View Container 和教程的 SplitViewController 之间嵌入 seagued。

一切都很好,直到我走到这一步:

Go to to AppDelegate.swift and replace the implementation of application(_:didFinishLaunchingWithOptions:) with the following:

guard let splitViewController = window?.rootViewController as? UISplitViewController,
  let leftNavController = splitViewController.viewControllers.first as? UINavigationController,
  let masterViewController = leftNavController.topViewController as? MasterViewController,
  let detailViewController = splitViewController.viewControllers.last as? DetailViewController
  else { fatalError() }

let firstMonster = masterViewController.monsters.first
detailViewController.monster = firstMonster

return true

应如何修改此代码以适用于我的案例?

在您的情况下,您无法访问 AppDelegate 中的 uisplitviewcontroller。由于您正在使用如下图所示的容器嵌入式视图。您从第一个 viewController 的 prepareFor segue 中获取 UISplitviewcontroller 的引用。因此,与其在 AppDelegate 中编写代码,不如尝试在初始 viewController.

中为 segue 做准备

初始ViewController class ViewController: UIViewController {

            @IBOutlet weak var containerView: UIView!
            override func viewDidLoad() {
                super.viewDidLoad()

                // Do any additional setup after loading the view.
            }

            override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

                if segue.identifier == "embedseg" {
                    guard let splitViewController = segue.destination as? UISplitViewController,
                        let leftNavController = splitViewController.viewControllers.first as? UINavigationController,
                        let masterViewController = leftNavController.topViewController as? MasterViewController,
                        let rightNavController = splitViewController.viewControllers.last as? UINavigationController,
                        let detailViewController = rightNavController.topViewController as? DetailViewController
                        else { fatalError() }

                    let firstMonster = masterViewController.monsters.first
                    detailViewController.monster = firstMonster

                    masterViewController.delegate = detailViewController

                    detailViewController.navigationItem.leftItemsSupplementBackButton = true
                    detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
                }

            }
        }