简体   繁体   English

在加载另一个ViewController时呈现模态视图控制器

[英]Presenting a modal view controller when loading another ViewController

Before the user can use my application he has to login. 在用户可以使用我的应用程序之前,他必须登录。 After he logged in, the database is built because I need information from the server to build it. 登录后,构建数据库是因为我需要来自服务器的信息来构建它。

Therefore my root ViewController is the LoginViewController which presents the actual application (a navigationController stack) modally on successful login. 因此我的根ViewController是LoginViewController,它在成功登录时以模态方式呈现实际应用程序(navigationController堆栈)。

If the user is already logged in on application launch (I am storing the credentials with NSUserDefaults) the LoginViewController should present the application immediately. 如果用户已在应用程序启动时登录(我使用NSUserDefaults存储凭据),则LoginViewController应立即显示应用程序。 Therefore I overwrote the method: 因此我覆盖了这个方法:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSInteger userId = [[NSUserDefaults standardUserDefaults] integerForKey:@"selfUser"];
    if (userId != 0) {
        //[self performSelector:@selector(presentMainViewController) withObject:nil afterDelay:2];
        [self presentMainViewController];
    }
}
- (void)presentMainViewController {
    mainViewController = [[MainViewController alloc] init];
    mainViewController.managedObjectContext = managedObjectContext;
    navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
    navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:navigationController animated:NO];
}

The [self presentMainViewController]; [self presentMainViewController]; is executed but the controller does not show up. 执行但控制器没有显示。 If I use the line above it does work. 如果我使用上面的行,它确实有用。

Where do I have to put the code to make it work? 我在哪里放置代码使其工作?

The view stack might not be completely created when viewDidAppear is send. 发送viewDidAppear时,可能无法完全创建视图堆栈。 So you should use the perfomSelector:withDelay to queue the call on the run loop. 因此,您应该使用perfomSelector:withDelay在运行循环上对调用进行排队。 In this way you can ensure that the view stack is build when your code runs. 通过这种方式,您可以确保在代码运行时构建视图堆栈。

Cheers! 干杯!

I had a similar situation and I resolved by moving the code to viewWillAppear (instead of viewDidAppear). 我有类似的情况,我解决了将代码移动到viewWillAppear(而不是viewDidAppear)。 It may worth to try. 值得一试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM