ios - 从 Objective-C 中的另一个类呈现 "Controller"
<p><p>如何呈现另一个类的 UIAlertController?</p>
<p>我想知道如何在 UIAlertController 中捕获“确定”按钮的操作,该 Controller 是在 B 类中创建但在 A 类中呈现的。</p>
<p>这就是我如何从 ClassA 调用在类“ErrorHandler”上创建警报的方法:</p>
<pre><code>ErrorHandler *handler = [ init];
animated:YES completion:nil];
</code></pre>
<p>这是ErrorHandler.m中alertWithInternetErrorCode的实现:</p>
<pre><code>- (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");
}];
;
return alert;
}
</code></pre>
<p>再次,我想知道如何能够在其他类中创建这类对象,并且仍然能够在您调用它们的类中呈现它们。这包括捕捉他们的行为。在这种情况下,它将是“取消按钮”内的 NSLog 操作。
是否可以调用方法而不是 NSLog?假设一个委托(delegate)方法并导航回 A 类中的代码?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>2 个选择:</p>
<p><strong>最佳选择:</strong></p>
<p>将 Controller 传递给方法,如下所示:<code>- (UIAlertController *)alertWithInternetErrorCodeInPresenter: (UIViewController *) presenter</code></p>
<p>调用<code>;</code></p>
<p><strong>如果这不可能:</strong></p>
<pre><code>UIViewController *rootVC = [[[ delegate] window] rootViewController];
;
</code></pre>
<hr/>
<h1>编辑——捕捉 Action :</h1>
<pre><code>- (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) {
;//Here's the key
}];
;
;
}
</code></pre>
<p>您必须在 <code>ErrorHandler.h</code> 文件中声明此协议(protocol):</p>
<pre><code>@protocol CustomAlertViewProtocol
- (void) cancelPressed;
@end
</code></pre>
<p>现在在您想要使用此方法的任何 ViewController.h 文件中,您必须告诉编译器您正在遵循 CustomAlertViewProtocol:</p>
<pre><code>@interface MyViewController : UIViewController <CustomAlertViewProtocol>
</code></pre>
<p>并且在.m中你必须实现协议(protocol)方法:</p>
<pre><code>- (void) cancelPressed {
//Do whatever you want
}
</code></pre>
<p>现在实际显示警报:</p>
<pre><code>ErrorHandler *handler = [ init];//Or whatever initializer you use
;
</code></pre></p>
<p style="font-size: 20px;">关于ios - 从 Objective-C 中的另一个类呈现"Controller",我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/38771374/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/38771374/
</a>
</p>
页:
[1]