Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popping a modal view from anywhere in code

Tags:

xcode

ios

iphone

Is it possible to 'pop' a view from any point in an iOS application.

For example, I want an event to trigger a view sliding in (modal) and the event can happen at any time, on any screen in the application.

Also, we'd like this to be something that can be included in other projects and would prefer them not to have to do anything special to these projects (other than wire in the referenced project).

like image 580
ConfusedNoob Avatar asked Sep 19 '12 03:09

ConfusedNoob


2 Answers

In this case you better play with the appdelegate, but it depends on what kind of application you are using.

create a method in appdelegate which you can call from any view controller

- (void)myMethod {
    MyController *myController = [[MyController alloc] init];
    [self.window.rootViewController presentModalViewController:myController animated:YES];
}

and for dismissing this controller you have to create action on the viewcontroller itself.

NOTE: you only can have 1 modelviewcontroller at a time so make sure your modelviewcontroller is a navigationcontroller itself inorder to stack all your views in it.

something like this,

- (void)myMethod {
     MyController *myController = [[MyController alloc] init];
     if([self.window.rootViewController modalViewController]) {
          [(UINavigationController *)self.window.rootViewController.modalViewController pushViewController:myController animated:YES];
     } else {
          UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myController];
           [self.window.rootViewController presentModalViewController:navController animated:YES];
     }
}
like image 173
Alex Markman Avatar answered Oct 22 '22 16:10

Alex Markman


I created this small recursive method to deal with this problem: https://gist.github.com/MartinMoizard/6537467

This is a category on UIViewController. You can basically call it from window.rootViewController.

like image 44
MartinMoizard Avatar answered Oct 22 '22 17:10

MartinMoizard