你是对的,这可以从应用程序委托级别完成application:viewControllerWithRestorationIdentifierPath:coder:
,但是您需要小心/切刀地执行此操作!
这里的目标是在状态恢复过程中返回一个 TNTLoginViewController ,并将其委托设置为其父级。
首先,您必须创建一个 TNTLoginViewController 对象。你提到了一个故事板,所以我将从那里加载它。我假设您有一个相当标准的 Main.storyboard 文件设置,并且在身份检查器中正确设置了身份。
TNTLoginViewController * loginViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"loginViewController"];
接下来,您需要将其委托设置为父级。我假设有一个 UINavigationController 连接这个模型。要从应用程序委托 https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfp/UIApplicationDelegate/window对象,您需要深入研究它的 window 属性。
window 属性是一个 UIWindow 对象,它有另一个属性称为根视图控制器 https://developer.apple.com/library/ios/documentation/uikit/reference/UIWindow_Class/UIWindowClassReference/UIWindowClassReference.html#//apple_ref/occ/instp/UIWindow/rootViewController。这是一个 UIViewController 对象。由于我假设有一个 UINavigationController 连接您的模型,因此您需要将此 UIViewController 类型转换为 UINavigationViewController (我会将无法放置在当前信誉级别的链接放置)。
现在,您可以使用导航堆栈顶部的控制器的 topViewController 属性,这就是您想要设置为委托的内容!如果没有,那么您可以导航您想要作为委托的对象的 UINavigationController 对象。
请记住,由于您是从应用程序委托级别设置委托,因此您可能需要在此处指定协议以避免模糊。
在代码中实现最后四个步骤将如下所示。
loginViewController.delegate = (id <TNTLoginViewControllerDelegate>)((UINavigationController *) self.window.rootViewController).topViewController;
然后您可以返回 TNTLoginViewController 并正确设置其委托!
确保不要忘记使用的含义application:viewControllerWithRestorationIdentifierPath:coder:
。您只想在恢复 TNTLoginViewController 的情况下执行此操作。幸运的是,您可以使用传入的identifierComponents参数来检查这一点。将其与身份检查器中的身份名称进行比较,如果不匹配则返回nil。
AppDelegate.m 文件中的最终方法将如下所示。
- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
{
if ([[identifierComponents lastObject] isEqualToString:@"loginViewController"]) {
TNTLoginViewController * loginViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"loginViewController"];
loginViewController.delegate = (id <TNTLoginViewControllerDelegate>)((UINavigationController *) self.window.rootViewController).topViewController;
return loginViewController;
}
return nil;
}
我希望这有帮助!