问题
I have a legacy codebase I am managing, which needs to display alert messages from all over the place. This is terrible practice and is in need of a refactor, but that isn't going to happen any time soon. With iOS 9 I need the ability to fire & forget an alert view, and have the view display and queuing managed for me.
回答1:
To show, UIAlertController
, we need object of UIViewController
So you can use below way to do that.
UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow];
UIViewController *mainController = [keyWindow rootViewController];
[mainController presentViewController:alert animated:YES completion:nil];
Thanks
回答2:
As other people have suggested, this is generally bad practice and breaks the MVC principles. However, if you're managing a legacy codebase and refactoring everything simply isn't an option, i made this class which lets you treat UIAlertController
like the old UIAlertView
, it manages displaying the alert from any class, and also queue's alerts for you...
https://github.com/sammio2/SMHAlertController
回答3:
For Display UIAlertController in NSObject class use below code.
UIAlertController * popup = [UIAlertController
alertControllerWithTitle:nil
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
[popup dismissViewControllerAnimated:YES completion:nil];
}];
[popup addAction:cancel];
UIViewController *rootViewController = [[Helper shareInstance] topViewController];
[rootViewController presentViewController:popup animated:YES completion:nil];
// Put Below Method in Your Global Helper Class.
- (UIViewController *)topViewController {
return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
- (UIViewController *)topViewController:(UIViewController *)rootViewController {
if (rootViewController.presentedViewController == nil) {
return rootViewController;
}
if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) {
UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
return [self topViewController:lastViewController];
}
UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
return [self topViewController:presentedViewController];
}
来源:https://stackoverflow.com/questions/31472321/how-do-i-display-uialertcontroller-from-any-nsobject-subclass