在Objective-C中呈现来自另一个类的“Controller”

如何从另一个类呈现UIAlertController?

我想知道如何捕获在B类中创建但在A类中呈现的UIAlertController中的“ok”按钮的操作。

这就是我如何从ClassA调用在类“ErrorHandler”上创建Alert的方法:

ErrorHandler *handler = [[ErrorHandler alloc] init]; [self presentViewController:[handler alertWithInternetErrorCode] animated:YES completion:nil]; 

这是ErrorHandler.m中alertWithInternetErrorCode的实现:

 - (UIAlertController *)alertWithInternetErrorCode{ UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"No internet conneciton" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { NSLog(@"cancelled"); }]; [alert addAction:cancel]; return alert; } 

同样,我想知道如何能够在其他类中创建这些类型的对象,并且仍然能够在您调用它们的类中呈现它们。 这包括捕捉他们的行动。 在这种情况下,它将是“取消按钮”内的NSLog动作。 是否可以调用一个方法而不是NSLog? 让我们说一个委托方法并导航回到A类中的代码?

2种选择:

最佳选择:

将控制器传递给方法如下: - (UIAlertController *)alertWithInternetErrorCodeInPresenter: (UIViewController *) presenter

调用[presenter presentViewController: alert animated:YES completion:nil];

如果这不可能:

 UIViewController *rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; [rootVC presentViewController:alert animated:YES completion:nil]; 

编辑 – 捕获操作:

 - (void) presentAlertWithInternetErrorCodeInPresenter:(UIViewController *) 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]; } 

ErrorHandler.h文件中,您必须声明此协议:

 @protocol CustomAlertViewProtocol - (void) cancelPressed; @end 

现在,在任何想要使用此方法的视图控制器.h文件中,必须告诉编译器您正在遵循CustomAlertViewProtocol:

 @interface MyViewController : UIViewController  

在.m中,您必须实现协议方法:

 - (void) cancelPressed { //Do whatever you want } 

现在实际显示警报:

 ErrorHandler *handler = [[ErrorHandler alloc] init];//Or whatever initializer you use [handler presentAlertWithInternetErrorCodeInPresenter: self];