CodeGuy
CodeGuy

Reputation: 28905

UIAlertView easy way to tell if cancel button is selected

I know I've done this before but I just can't figure it out again.

What is the method I would use to see if a cancel button was pressed. I don't want to do it based on the button index. There is a way to do it, something like:

[alertView isCancelIndex:index];

Anyone know?

Upvotes: 14

Views: 19323

Answers (3)

Eman yalpsid
Eman yalpsid

Reputation: 511

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

  if (buttonIndex == [alertView cancelButtonIndex]) {
    NSLog(@"The cancel button was clicked for alertView");
  }
// else do your stuff for the rest of the buttons (firstOtherButtonIndex, secondOtherButtonIndex, etc)
}

Upvotes: 32

Paul Warkentin
Paul Warkentin

Reputation: 3899

In the delegate of UIAlertView is the method

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

And then:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger cancelIndex = [alertView cancelButtonIndex];
    if (cancelIndex != -1 && cancelIndex == buttonIndex)
    {
        // Do something...
    }
}

Upvotes: 2

rich
rich

Reputation: 2136

The UIAlertView has a property of cancel button index

@property(nonatomic) NSInteger cancelButtonIndex

Usage

[alertView cancelButtonIndex]

Upvotes: 53

Related Questions