问题
In my subclass of NSObject
I would like to call something like
[[self navController] presentModalViewController:myView animated:YES];
But none of my tries were successful. How can I call a modal view if I'm not in a subclass of UIViewController
?
Solution:
#import "myProjectNameAppDelegate.h"
// ...
MyViewController *myView = [[MyViewController alloc] init];
myProjectNameAppDelegate *appDelegate = (myProjectNameAppDelegate *)[[UIApplication sharedApplication] delegate];
[[appDelegate navController] presentModalViewController:myView animated:YES];
回答1:
I don't see a way to display a modal view without a ViewController. You have to store a reference to a UIViewController in your class so you can access it. Or setup a property in your AppDelegate, which you can get by calling [[UIApplication sharedApplication] delegate];
回答2:
better way to call a presentModalViewController is, passing viewcontroller
to the NSobject
class. call the nsobject
function from the uiviewcontroller
Here is the code with mail example
In view Controller //your current view
[nsobjectclassObject OpenMailComposer:self];
//this will take the viewcontroller to NSobject
class
In NSObject class //may be sharing class
-(void)OpenMailComposer:(UIViewController*)view
{
viewControllertoShow = view; // viewControllertoShow is UIVIewcontroller object
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc]init];
mailView.mailComposeDelegate = self;
[mailView setSubject:@"Hey! check this out!"];
[viewControllertoShow presentModalViewController:mailView animated:YES];
}
For dismissing from NSObject class
you can do the following
[viewControllertoShow dismissViewControllerAnimated:YES]
回答3:
If you hold the navigationController or some viewController, you can present a modal view controller.
What is your myView
? Is it a view, is it a viewController. I hope that it is a viewcontroller otherwise, this is the reason your code doesn't run
来源:https://stackoverflow.com/questions/3760286/call-presentmodalviewcontroller-from-nsobject-class