ios - 无法获取对 UIViewcontroller 的引用

标签 ios swift uiviewcontroller

我有这个:

guard let mapVC = mapSB.instantiateInitialViewController() else { return }

mapVC.navigationItem.title = "Some title string"
//        (mapVC as! MapViewController).string = "Some string"
//        (mapVC.navigationController?.viewControllers.first as! MapViewController).string = "Some string"

我已经尝试了两行注释掉的行,但是无论我注释掉哪一行,它都会崩溃。这是mapVC的po:

po mapVC
error: <EXPR>:3:1: error: use of unresolved identifier 'mapVC'
mapVC
^~~~~~~~~

这很奇怪,因为它确实将 mapVC.navigationItem.title 正确设置为“某些标题字符串。”

如果这有帮助,mapVC 会嵌入到 mapSB 的导航 Controller 中。

编辑:

崩溃消息是:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

mapVC 是 MapViewController 类型,因此需要进行转换。

最佳答案

不要将该 View Controller 嵌入该 Storyboard 中的导航 Controller 中(这可能不会被拾取,因为您期望您的 instantiateViewController 返回 MapViewController),而是尝试创建导航 Controller 以编程方式,如下所示:

guard let mapVC = mapSB.instantiateInitialViewController() as? MapViewController else { fatalError("couldn't load MapViewController") }
mapVC.navigationItem.title = "Some title string"

// assuming mapVC has a .string property
mapVC.string = "Some string"

let navController = UINavigationController(rootViewController: mapVC) // Creating a navigation controller with mapVC at the root of the navigation stack.
self.presentViewController(navController, animated:true, completion: nil)

更多信息可见in this related question .

关于ios - 无法获取对 UIViewcontroller 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610162/

相关文章:

ios - 在 iPhone 上同时打开闪光灯和前置摄像头

ios - Swift 4 - 在我的 RESTful API 调用中是 "Background Thread?"

ios - 弹出到导航堆栈中的特定 View Controller

ios - 如何使两个 Collection View 出现在同一个 View Controller 上?

iOs:在启动时,转到指定的 View Controller

ios - 如何在我的代码中使用默认的 LoginWithFacebook 按钮

objective-c - 错误消息 : "index 1 beyond bounds"

ios - 在边界内点击手势识别器

ios - Swift - 当应用程序进入后台状态时,从 AppDelegate 更新 RootViewController 中的值

ios - 如果我实现 decidePolicyFor navigationAction,WKWebView 为空,如果我删除该功能,则正确加载