简短回答,如果您通过设置窗口的根从登录 UI 到应用程序的主 UI,那么这是返回的好方法。
// in some view controller in your app when you need to change to the login UI
UIStoryboard *storyboard = [self storyboard];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"MyLoginVCIdentifier"];
UIWindow *window = [UIApplication sharedApplication].delegate.window;
window.rootViewController = vc;
更长的答案,我有时会使用一个视图控制器,它唯一的工作就是管理这个,称之为LaunchViewController。
在我的 main.storyboard 中,我创建了一个 LaunchViewController 的实例并将“Is Initial View Controller”设置为 true。
这个 VC 不需要 UI,因为它唯一的工作就是在它出现时立即替换它自己。但是,由于我什至不希望在 LaunchScreen.storyboard 之后出现瞬间闪烁,因此有时我会这样做以将这个 vc 的视图与启动故事板视图重叠,但这部分是可选的....
// LaunchViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
UIStoryboard *storyboard = [self.class storyboardWithKey:@"UILaunchStoryboardName"];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"LaunchVC"];
[self.view addSubview:vc.view];
}
// a convenience method to get a storyboard from the bundle by key
+ (UIStoryboard *)storyboardWithKey:(NSString *)key {
NSBundle *bundle = [NSBundle mainBundle];
NSString *storyboardName = [bundle objectForInfoDictionaryKey:key];
return [UIStoryboard storyboardWithName:storyboardName bundle:bundle];
}
回到您的问题,我的 LaunchViewController 提供了一种方法,该方法在给定故事板标识符的情况下呈现(带有您选择的动画)主故事板视图控制器...
// LaunchViewController.m
+ (void)presentUI:(NSString *)identifier {
UIStoryboard *storyboard = [self storyboardWithKey:@"UIMainStoryboardFile"];
UINavigationController *vc = [storyboard instantiateViewControllerWithIdentifier:identifier];
UIWindow *window = [UIApplication sharedApplication].delegate.window;
window.rootViewController = vc;
[UIView transitionWithView:window
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:nil
completion:nil];
}
这样,我们可以给LaunchViewController 任意数量的公共方法,比如...
+ (void)presentLoginUI {
[self presentUI:@"IdentifierOfMyLoginViewController"];
}
+ (void)presentMainAppUI {
[self presentUI:@"IdentifierOfMyMainAppViewController"];
}
由于系统窗口只有一个指向根视图控制器的指针,而您在 presentUI: 中替换了该指针,ARC 将为您清理整个丢弃的 UI。