2017-06-17 63 views
0

我有这样的:无法获取引用到的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 mapVC 
error: <EXPR>:3:1: error: use of unresolved identifier 'mapVC' 
mapVC 
^~~~~~~~~ 

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

如果这有帮助,mapVC被嵌入到mapSB的导航控制器中。

编辑:

碰撞信息是:

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

而mapVC是类型的MapViewController,因此铸造的。

+0

故事板中初始视图控制器的类是什么? –

+0

什么是崩溃消息? – Paulw11

回答

0

而是嵌入在一个导航控制器,视图控制器,故事板内(这可能是没有被拾起,因为你期待你的instantiateViewController返回一个MapViewController)的,尝试创建导航控制器编程,像这样:

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

0

试试这个。

guard let navigationVC = mapSB.instantiateInitialViewController() as? UINavigationController, 
     let mapVC = navigationVC.viewControllers.first as? MapViewController else { 
      return 
    } 

    mapVC.navigationItem.title = "Some title string" 
    mapVC.string = "Some string" 

如果您最初MapViewController嵌入在UINavigationController,然后mapSB.instantiateInitialViewController()将会返回嵌入UINavigationController实例。因此,您需要致电navigationVC.viewControllers.first以获取您的MapViewController实例。

在您最初的代码中,行

(mapVC as! MapViewController).string = "Some string" 

失败,因为mapVC不是的MapViewController一个实例,因此使用as! MapViewController导致崩溃。

as!操作者也导致崩溃在此行

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

mapVC由于是根导航控制器,mapVC.navigationController的计算结果为nil。因此mapVC.navigationController?.viewControllers.first解决为nil,并试图强制转换nilas! MapViewController导致崩溃。

相关问题