IOS: two button control in a UIAlert
I have this code in a IBAction:
UIAl开发者_JAVA百科ertView *alertView = [[UIAlertView alloc] initWithTitle:@"NO!"
message:@"danger"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:@"Annul", nil];
[alertView show];
[alertView release];
Now if I push "OK" it must do a thing and if I push "Annul" it must do another thing. But it must be done inside the IBAction.
You need to implement UiAlertViewDelegate
method.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
So the delegate function should be like below.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)//OK button pressed
{
}
else if(buttonIndex == 1)//Annul button pressed.
{
}
}
Jhaliya's answer is great, except it doesn't address blackguardian's request to run this inside a IBAction
method. Having an IBAction method block and wait for a response from the UIAlertView is the wrong way to work in CocoaTouch. The IBAction
should just present the UIAlertView. Then the delegate function in Jhaliya's answer should parse which way to proceed, "OK", or "Annul". This delegate function can then perform the action (possibly by calling further methods). CocoaTouch's event handling is not designed for IBAction
methods to block awaiting further user input.
Think of the chain IBAction->UIAlertView->alertView:clickedButtonAtIndex:
as just the IBAction
when not using an UIAlertView
, and place your current code in the IBAction
after this chain.
精彩评论