我正在尝试在单个View Controller中执行两个警报的微笑任务。下面的代码工作正常,但我如何在View Controller的其他地方创建它的另一个实例。我担心如果我复制代码,我的buttonIndex将不知道它正在响应哪个警报。有任何想法吗?谢谢!
-(void)alertChoice
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
//do something
}
}
答案 0 :(得分:25)
您可以使用tag
上的UIAlertView
属性来解密哪个提醒:
-(void)alertChoice
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
alert.tag = 0;
[alert show];
}
-(void)alertChoice1
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
alert1.tag = 1;
[alert1 show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 0)
{
}
}
答案 1 :(得分:2)
将标记设置为警报视图。
alert.tag = 1;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1 && alertView.tag == 1)
{
//do something
}
}
答案 2 :(得分:2)
只需为每个警报视图设置一个标签,并检查哪一个发送了messeg。
alertView.tag=0;
然后
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(alertView.tag==0){
if(buttonIndex == 0)//OK button pressed
{
//do something
}
else if(buttonIndex == 1)//Annul button pressed.
{
//do something
}
}else{
if(buttonIndex == 0)//OK button pressed
{
//do something
}
else if(buttonIndex == 1)//Annul button pressed.
{
//do something
}
}
答案 3 :(得分:1)
步骤1:在视图controller.h文件中添加 UIAlertViewDelegate
第2步:在view controller.m文件中添加以下方法
-(void)AlertMethodOne
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"AlertMethodOne" message:@"AlertMethodOne successfully Called" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
alert.tag=101;
[alertview show];
}
-(void)AletrMethodTwo
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"AletrMethodTwo" message:@"AlertMethodTwo successfully Called" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
alert.tag=102;
[alertview show];
}
在viewController中调用上面两个方法,如下所示: [self AlertMethodOne]; [self AlertMethodTwo];
现在AlertView按钮单击方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag==101)
{
if (buttonIndex == 0)
{
}
}
if(alertView.tag==102)
{
if (buttonIndex == 1)
{
}
}
}