没有从 AppDelegate 设置 RootViewController?
Posted
技术标签:
【中文标题】没有从 AppDelegate 设置 RootViewController?【英文标题】:RootViewController not being set from AppDelegate? 【发布时间】:2015-08-12 13:27:36 【问题描述】:我正在使用归档对象来确定需要在启动时(或仅从睡眠状态打开应用程序)加载布尔标志的视图。尽管我的 if 语句评估正确,但其中的代码却没有。
这是 didFinishLaunchingWithOptions 中的内容:
// Register permission to throw notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Badge | .Sound, categories: nil))
var so = StatusOverseer.sharedOverseer
println("User did finish application: \(so.userDidFinishApplication)")
println("Banks Did Respond: \(so.banksDidRespond)")
println("user did accept terms: \(so.userDidAcceptTerms)")
// Decide whether or not to present the waiting view
if so.userDidFinishApplication && !so.banksDidRespond
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("submitWaiting") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
else if so.banksDidRespond
println("bip")
let sb = UIStoryboard(name: "Main", bundle: nil)
if so.notificationWasGood
let vc = sb.instantiateViewControllerWithIdentifier("approved") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
else
let vc = sb.instantiateViewControllerWithIdentifier("notApproved") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
else if so.userDidAcceptTerms
println("Did Run")
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("LicenseViewNav") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
这是控制台输出:
Recalling Status Overseer from Archive...
User did finish application: false
Banks Did Respond: false
user did accept terms: true
Did Run
请注意,底部 else if
按预期运行,但我在启动时看到的视图不是 LicenseViewNav
行中声明的:
let vc = sb.instantiateViewControllerWithIdentifier("LicenseViewNav") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
如果有人知道发生了什么,那就太好了。谢谢!
编辑:当前问题似乎是 keyWindow
评估为 nil
【问题讨论】:
你检查过keyWindow
是不是nil
吗?您是否使用故事板来创建界面?
刚刚检查过。看起来是nil
,是的,我正在使用情节提要。
【参考方案1】:
在 swift 中设置根视图控制器的最佳方法
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
var rootView: MyRootViewController = MyRootViewController()
if let window = self.window
window.rootViewController = rootView
return true
【讨论】:
【参考方案2】:这是一个通过强制 keyWindow 初始化的简单修复。我只是将这一行放在我的 if 语句之上,它现在可以工作了。
window?.makeKeyAndVisible()
【讨论】:
以上是关于没有从 AppDelegate 设置 RootViewController?的主要内容,如果未能解决你的问题,请参考以下文章
从 appdelegate 设置 UIViewController 委托
无法从 appdelegate.m 为 NSProgressIndicator 设置动画
从 Appdelegate 设置 iBeacon 操作和监控
如果 UITabbarcontroller 不是 rootviewcontroller,如何从 Appdelegate 为 UIBarButtonItem 设置徽章(无论何时推送通知)?