带有标签的多个 AlertView,无法取消

Multiple AlertView with tags, can't cancel

我在 Stack 中搜索了实现多个 alertViews 的方法。大多数答案是使用标签。这种方式效果很好,除了一个巨大的东西 - 取消按钮!当 alertView 弹出时,无论您点击“取消”还是“yourButtonTitle”,您的操作都会成功。有没有办法取消带有标签的 alertView

这是我的代码:

#define TAG_ONE 1
#define TAG_TWO 2

- (IBAction)someButton1 {

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Call" message:@"Call number?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call", nil];

alertView.tag = TAG_ONE;
[alertView show];
}

- (IBAction)someButton2 {

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Log Out?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];

alertView.tag = TAG_TWO;
[alertView show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

if (alertView.tag == TAG_ONE) { 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:101-101-1010"]];

} else if (alertView.tag == TAG_TWO){ 
    [PFUser logOut];
    [self performSegueWithIdentifier:@"showLogin" sender:self];
}
}

您可以仅为 UIAlertview 设置 TAG,但您可以使用按钮 Index

识别 button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

if (alertView.tag == TAG_ONE) {
if(alertView.cancelButtonIndex == buttonIndex){
// Do cancel
}
else{
// Do the success thing
}
}
else if (alertView.tag == TAG_TWO) {
// same thing followed
}
}

buttonIndex == 0 // OK , buttonIndex == 1 // Cancel

额外Reference

您必须在询问之前添加 if (alertView.cancelButtonIndex == buttonIndex){ // Do cancel } if (alertView.tag == TAG_ONE) {