我有这个:
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中的导航控制器中。
编辑:
崩溃讯息是:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
mapVC是MapViewController类型,因此是转换。
答案 0 :(得分:0)
不是将该视图控制器嵌入到该故事板中的导航控制器中(可能因为您期望instantiateViewController
返回MapViewController而未被拾取),请尝试以编程方式创建导航控制器 / em>,像这样:
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。
答案 1 :(得分: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
,并尝试强制转换nil
as! MapViewController
会导致崩溃。