Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

presentViewController in viewDidLoad

I'm trying to use presentViewController from viewDidLoad using this code:

@implementation ViewController

- (void)showLogin{
    id animator = [[MyCustomAnimator alloc] init];
    NSViewController* vc = [[MyViewController alloc] initWithNibName:nil bundle:nil];

    [self presentViewController:vc animator:animator];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Presenting ViewController";
    [self showLogin];
}

@end

It works fine when I call it from a IBAction button but doing it programatically I'm getting this error:

 *** Assertion failure in -[ViewController presentViewController:animator:], /Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1404.12/Controllers/NSViewController.m:826

Failed to set (contentViewController) user defined inspected property on (NSWindow): presentViewController:animator:: View '<ViewController: 0x6000000c28b0>''s view is not in a window/view hierarchy.

Not sure how to proceed, could anyone point me in the right direction?

like image 479
Enemy Avatar asked Oct 25 '15 16:10

Enemy


1 Answers

You're doing this way too soon. viewDidLoad means that the view controller has a view (that's what the word "load" means), but that view is not part of the interface. Thus, there is nothing to present from.

Wait until viewDidAppear:. That means that the view controller's view is in the interface (that's what the word "appear" means).

Beware, though, that viewDidAppear: can be called multiple times, and will be called when the presented view controller is dismissed, giving you a vicious circle. Use a Bool flag (a property) of some sort to prevent that.

like image 52
matt Avatar answered Oct 01 '22 23:10

matt