Determining which button was pressed in one of the two UIAlertViews
I开发者_开发问答 have two UIAlertView's which are not displayed one after another. Both of the have two buttons and I need to determine which button was pressed. I've tried to use
- (void)alertOKCancelAction {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0)
{ //Code
}
else
{//Code
}
}
But this code doesn't work if I have two UIAlertViews.
Can you help me? Thanks in advance!
Looks like you might be able to optimize your design a little bit. Why not wrap a method around your UIAlertView, then pass in the information you need to display the alert.
Then use
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
{
NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
//....Do something based on the btnTitle that was clicked.
}
To check which button was clicked based on the title.
Another option that would require less resources is to just assign a tag value to each Alert Window. The method listed above does work but comparing strings adds a little more memory use than just using tag values. By assigning tag values to each tag you can still use the clickedButtonAtIndex option and then you just need to check which Alert View was clicked:
NSInteger alertTag = alertView.tag
if (alertTag == 1) {
if (buttonIndex == 0 {
//do something based on first Alertview being clicked
}
}
if (alertTag == 2) {
...continue as much as you need
I did this in one of my apps since there were Web Services being called (so we needed to check for network connections and show an alert to retry the call) and also had alerts that came up for some of the other interactions as well. Using the tag option above made it really easy to determine which alertview was being interacted with.
精彩评论