2个选择:
最佳选择:
将控制器传递到方法中,如下所示:- (UIAlertController *)alertWithInternetErrorCodeInPresenter: (UIViewController *) presenter
Call [presenter presentViewController: alert animated:YES completion:nil];
如果这不可能:
UIViewController *rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[rootVC presentViewController:alert animated:YES completion:nil];
编辑 - 捕获操作:
- (void) presentAlertWithInternetErrorCodeInPresenter:(UIViewController<CustomAlertViewProtocol> *) presenter{
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@"Error"
message:@"No internet connection"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancel = [UIAlertAction
actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
[presenter cancelPressed];//Here's the key
}];
[alert addAction:cancel];
[presenter presentViewController: alert animated:YES completion:nil];
}
In the ErrorHandler.h
文件中您必须声明此协议:
@protocol CustomAlertViewProtocol
- (void) cancelPressed;
@end
现在,在任何要使用此方法的视图控制器 .h 文件中,您必须告诉编译器您正在遵循 CustomAlertViewProtocol:
@interface MyViewController : UIViewController <CustomAlertViewProtocol>
在 .m 中,您必须实现协议方法:
- (void) cancelPressed {
//Do whatever you want
}
现在实际显示警报:
ErrorHandler *handler = [[ErrorHandler alloc] init];//Or whatever initializer you use
[handler presentAlertWithInternetErrorCodeInPresenter: self];