UIAlertView runModal

3

回答iOS SDK中NSAlert.h在哪里?的问题。

是否有办法从UIAlertView或UIActionSheet中获得类似于NSAlert runModal的行为?

我计划仅在调试版本中使用,因此不关心它的外观或是否使用了未记录的功能。

编辑:

NSAlert是OS X SDK的一部分,类似于Win32中的MessageBox。它允许您同步提示用户进行某些操作。以下是一个示例:

NSAlert * myAlert=[[NSAlert alloc] init];
[myAlert setMessgeText:@"This is my alert"];
[myAlert addButtonWithTitle:@"button 1"];
[myAlert addButtonWithTitle:@"button 2"];

switch ([myAlert runModal]) {
  case NSAlertFirstButtonReturn:
    //handle first button
    break;
  case NSAlertSecondButtonReturn:
    //handle second button
    break;
}

runModal是一个同步函数,它显示警报并等待用户响应。在内部,它运行着一个有限版本的消息循环,但就我的应用程序而言,世界已经停止了;没有消息,没有事件,什么都没有。


不熟悉 NSAlert。也许你可以解释一下它的行为? - Erik B
所以您需要重新标记此问题,与iOS、UIAlertView或UIActionSheet无关。 - bshirley
2个回答

9

内部运行的是消息循环的有限版本,但对于我的应用程序的其余部分来说,世界已经停止了。

只需按照您描述的方式执行:弹出警报,然后运行事件循环直到警报视图被解除。这段代码可以正常工作:

UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"O rlly?" message:nil delegate:nil
        cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
NSRunLoop *rl = [NSRunLoop currentRunLoop];
NSDate *d;
while ([alert isVisible]) {
    d = [[NSDate alloc] init];
    [rl runUntilDate:d];
    [d release];
}
[alert release];

这里没有防止重入的保护。如果他的代码重新进入此逻辑,它将弹出另一个警报。 - Ian Baird
大多数iOS代码不可重入。此解决方案足以用于调试目的,这也是OP想要的。 - Jeremy W. Sherman
我之前尝试过类似这样的代码:do {[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];} while (alertView.visible);,但有时候会陷入循环而没有弹出警告框。我可能应该在问题中提到这一点。 - IronMensan
在这种情况下,有没有办法找出按下了哪个按钮? - anticyclope

0

如果您想要这种行为,就必须自己编写。请注意,如果您阻塞主队列时间过长,您的应用程序将被监视。

UIAlertView 提供了模态行为,并且最终会以与自定义类相同的方式工作。您可以考虑使用基于块的包装器来包装 UIAlertView,并允许您设置按钮操作回调的块。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接