I am trying to detect whether the user pressed the cancelButton or destructive button on the actionSheet. Depending on his/her input, I would like to modify the alert message shown on the screen.
So I tried using if to check the buttonIndex, but it turns out that the buttonIndex value does not change with the input from the user.
UIActionSheet *informUser = [[UIActionSheet alloc] initWithTitle:@"Missing data" delegate:self cancelButtonTitle:@"Thanks for telling me!" destructiveButtonTitle:@"I have ignored it!" otherButtonTitles:nil];
[informUser showInView:self.view];
// NSLog(@"Cancel button = %d", informUser.cancelButtonIndex);
// NSLog(@"Destructive button = %d", informUser.destructiveButtonIndex);
if(informUser.cancelButtonIndex == 1)
{
NSString *msg = [[NSString alloc] initWithFormat:@"Pls enter the number."];
UIAlertView *alertUser = [[UIAlertView alloc] initWithTitle:@"Missing data" message:msg delegate:self cancelButtonTitle:@"Thanks!" otherButtonTitles:nil];
[alertUser show];
}
I also tried using a separate method:
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex;
but, I get wrong results when I have multiple UIAlert at different points on the same screen.
In short, I would like to use a different UIAlert for different actions/inputs from user. Therefore, how do I detect which button on the actioSheet has been pressed by the user?
Thank you.
Implement the
UIActionSheetDelegateand use the method:The index defines which button you tapped.
If you don’t want to use the button index you can get the button title of the tapped button with
Then you can compare the result to your button title string.
Read more in the Apple docs
Edit:
If you want to use more actionsheets you can set the tag-value for each of them. E.g. ActionSheet1 has actionsheet.tag = 1 and so on.
Then you can switch in
– actionSheet:clickedButtonAtIndex:by the tag of the given actionsheet. E.g.:Edit 2:
This is a sample class that should show you the logic:
Header file:
Implementation file: