Objective C: AlertView does not work
I am implementing an alert view after the user clicks on the 'destructButton' in an action sheet. Code snippet as below:
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != actionSheet.cancelButtonIndex)
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Something happened!"
message:nil
delegate:nil
cancelButtonTitle:@"Phew!"
otherButtonTitles:nil];
}
[alert show];
[alert release];
}
I have already included the UIActionSheetDelegate protocol in my .h file
@interface Control_FunViewController : UIViewController <UIActio开发者_运维百科nSheetDelegate> {
UITextField *nameField;
UITextField *numberField;
UILabel *sliderLabel;
UISwitch *leftSwitch;
UISwitch *rightSwitch;
UIButton *doSomethingButton;
}
But when I click on the destructButton in the actionsheet, nothing happens. Am I missing something here?
Thanks
Zhen
Your delegate needs to implement actionSheet:clickedButtonAtIndex:
.
Action sheet will be dismissed after actionSheet:clickedButtonAtIndex:
and after that the delegate will receive actionSheet:didDismissWithButtonIndex:
.
From Apple Action Sheet Delegate Protocol reference
... the delegate must implement the actionSheet:clickedButtonAtIndex: message to respond when those buttons are clicked; otherwise, your custom buttons do nothing. The action sheet is automatically dismissed after the actionSheet:clickedButtonAtIndex: delegate method is invoked.
You can have a look at example projects that use UIActionSheet like GenericKeychain :
// Action sheet delegate method.
- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0)
{
[passwordItem resetKeychainItem];
[accountNumberItem resetKeychainItem];
[self.tableView reloadData];
}
}
You have added UIActionSheetDelegate on .h file. Not this only enough. You also have to set delegate for the UIActionSheet object. Refer this below coding:
-(void)showActionSheet { UIActionSheet *action =[[UIActionSheet alloc]initWithTitle:@"dsfs" delegate:self cancelButtonTitle:@"First Btn" destructiveButtonTitle:@"Dest Btn" otherButtonTitles:nil]; [action showInView:self.view];
}
In that code, I have set the delegate of UIActionSheet to self, this works if you have added this method on your ViewController (Control_FunViewController).
精彩评论