【发布时间】:2017-04-06 19:45:23
【问题描述】:
我知道这个问题已经被问过无数次了,而且我看到了很多变化,包括
func performSegue(withIdentifier identifier: String,
sender: Any?)
以及此处提到的所有其他变体:How to call a View Controller programmatically
但是您将如何更改 ViewController 类之外的视图控制器?例如,用户当前在ViewController_A 上,当蓝牙设备已断开连接(超出范围、信号弱等)时,CBCentral 的didDisconnectPeripheral 方法被触发。在同样的方法中,我想将当前视图更改为ViewController_B,但是这种方法不会出现在ViewController 类中,所以像performSegue 这样的方法将不起作用。
我在AppDelegate 中实施的一个建议似乎可行(用于获取适合 iphone 屏幕尺寸的故事板文件/我非常讨厌AutoLayout)
var storyboard: UIStoryboard = self.grabStoryboard()
display storyboard
self.window!.rootViewController = storyboard.instantiateInitialViewController()
self.window!.makeKeyAndVisible()
然后我尝试在我的非ViewController 类中做同样的事情
var window: UIWindow?
var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) //assume this is the same storyboard pulled in `AppDelegate`
self.window!.rootViewController = storyboard.instantiateViewController(withIdentifier: "ViewController_B")
self.window!.makeKeyAndVisible()
但是我得到一个异常抛出说fatal error: unexpectedly found nil while unwrapping an Optional value大概来自window!
对我能做什么以及正确的设计模式有什么建议?
【问题讨论】:
-
你需要先初始化你的
windowvar,然后再尝试解包。
标签: ios swift uiviewcontroller segue