19

How can I dismiss UIAlertView ? This code doesn't work.

@property (nonatomic, retain) UIAlertView *activityAlertView;
- (void)viewDidLoad 
{
self.activityAlertView = [[UIAlertView alloc] initWithTitle:@"Receiving data" message:@"\n\n"
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                                otherButtonTitles:nil, nil];  
[activityAlertView show];
}

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

-(void) myfunc
{
[self alertView:activityAlertView clickedButtonAtIndex:1];
}
benwong
  • 2,226
  • 1
  • 16
  • 14
Voloda2
  • 12,359
  • 18
  • 80
  • 130

2 Answers2

57

The - (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated method of the UIAlertView class does what you want. eg:

[myAlertView dismissWithClickedButtonIndex:-1 animated:YES];
Salmo
  • 1,788
  • 1
  • 18
  • 29
JustSid
  • 25,168
  • 7
  • 79
  • 97
  • 4
    It’s probably cleaner to use the cancel button index: `[myAlertView dismissWithClickedButtonIndex: myAlertView.cancelButtonIndex animated:YES];`. – Vincent Tourraine Feb 09 '15 at 09:23
  • @VincentTourraine Ouh, old answer you dug up there. If the cancel button index is the correct one depends on the behaviour you want. If you just want to dismiss the alert, `-1` is the way to go. If yo prefer to run through the cancel case, the cancel button index is correct. – JustSid Feb 09 '15 at 09:25
5

Since you are using a delegate callback method of UIAlertView, I think it is better you use the following code

[myAlertView dismissWithClickedButtonIndex:0 animated:YES]; 

if not then use the above suggested code

[myAlertView dismissWithClickedButtonIndex:-1 animated:YES];
marian0
  • 664
  • 6
  • 15