2017-06-17 64 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導致崩潰。

相關問題