在我看来,解决此类问题的最佳策略是在应用程序启动时在主视图控制器上显示登录屏幕,并在用户登录后很好地关闭并释放。我发现大多数先前建议的解决方案(以及这里的建议:Storyboard 登录屏幕的最佳实践,处理注销时清除数据 https://stackoverflow.com/questions/19962276/best-practices-for-storyboard-login-screen-handling-clearing-of-data-upon-logou)不要优雅地完成这个任务。
经过昨天的一些实验,我认为最好的方法是使用子视图控制器:
1. 像平常一样在 Xcode 中选择主界面故事板(无需向您的主界面添加任何内容)appDelegate
2. 将以下内容添加到主视图控制器中viewDidLoad
:
// If user is not logged in, show login view controller
if (!isLoggedIn) {
// Instantiate Login View Controller from storyboard
UIStoryboard *mainSB = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *loginVC = [mainSB instantiateViewControllerWithIdentifier:@"Login"];
// Set the Login View Controller's frame
loginVC.view.frame = self.view.bounds;
// Add login screen as a subview and as a child view controller
[self.view addSubview:loginVC.view];
[self addChildViewController:loginVC];
[loginVC didMoveToParentViewController:self];
// Maintain a reference to the Login screen so we can dismiss it later
_loginVC = loginVC;
}
3. 用户登录后,通过使用通知或委托通知您的主视图控制器。然后,您可以按照您希望的方式将登录屏幕动画化。这里我使用的是溶解动画:
// Animate out the category chooser
[UIView animateWithDuration:0.2 animations:^{
// Dissolve the login screen away
[_loginVC.view setAlpha:0];
} completion:^(BOOL finished) {
// Remove login screen as a child view controller
[_loginVC willMoveToParentViewController:nil];
[_loginVC.view removeFromSuperview];
[_loginVC removeFromParentViewController];
// nil out property
_loginVC = nil;
}];
就是这样!这样,主视图控制器始终是窗口的根视图控制器,用户登录后登录屏幕将被释放,并且首次呈现登录屏幕时不会出现闪烁。