以编程方式关闭UIAlertView

13

我需要帮助以编程的方式解散UIAlertView。 目前我有这个:

UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];

然后稍后我调用这个:

[alert1 dismissWithClickedButtonIndex:0 animated:NO];

但是没有任何反应。


3
当您调用 "dismissWithClickedButtonIndex" 时,"alert1" 是否为非空值? - Michael Dautermann
你是在同一段代码块中调用 showdismiss 吗?这样做不会起作用,因为 show 需要时间来执行。 - vakio
不,dismiss被有条件地延迟调用。 - Nick P
你如何到达“后来”?你应该告诉我们更多关于你正在做什么的信息... - Taum
@Nick P 委托:self和两个按钮引用都设置为nil,因此dismissWithClickedButtonIndex将没有任何引用。您需要至少设置一个otherButtonTitles标题值:@“继续”,nil - Charles Robertson
5个回答

35

您需要设置两件事。

1. 包括您的.h文件: <UIAlertViewDelegate>

2. 请按照以下实现方式进行操作...

   UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]; 
        [alert1 show];
        [self performSelector:@selector(dismiss:) withObject:alert1 afterDelay:1.0];

dismiss方法将会...

-(void)dismiss:(UIAlertView*)alert
{
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

希望这能对你有所帮助。


5
我是你的助手,接下来为您翻译以下内容:

我也遇到了这个问题。在我的情况下,由于某种原因调用:

[alert dismissWithClickedButtonIndex:0 animated:NO];

即使在 UI 线程调用,而且 alert != nil,有时候调用并不起作用,相反,只需将 animated 标志设置为 YES 就可以了:

[alert dismissWithClickedButtonIndex:0 animated:YES];

也许这是苹果的一个漏洞...

3

首先要显示它:

UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    [alert1 show];

然后在委托方法中。
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if(buttonIndex==0){
     // do something
    }
}

只有在 O.P. 在创建警报时正确设置了委托,该委托方法才会被调用。 - Michael Dautermann
我忘了说,我已经像你描述的那样显示出来了。我尝试了这个,但结果却相同。什么都没有发生。 - Nick P
1
你设置了 alert1 的代理吗? - Mil0R3
是的,但我不知道要放什么。 - Nick P

0

你可以使用代理方法-alertView:didDismissWithButtonIndex:来替代,它会在警告视图从屏幕上移除后被调用。或者更好的方法是,使用后台线程,例如-performSelectorInBackground:withObject:,来处理你需要做的任何处理。


0
你调用的方法是正确的。
我猜测当你调用dismissWithClickedButtonIndex:animated:方法时,alert1可能是nil。
尝试检查你的变量alert1。

我刚刚检查了一下,在调用该方法时它不是nil。 - Nick P

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