Action sheets display a set of buttons representing several alternative choices to complete a task initiated by the user. In this tutorial we will display an action sheet and we will log the selected button.
Open Xcode and create a new Single View Application. For product name, use iOS7ActionSheetTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.
Open the storyboard and drag a button to the main view. Give the button the text "Display Action Sheet".
Select the Assistant Editor and open ViewController.m, Ctrl + drag from the Button in our storyboard to the interface section of ViewController.m and make the following IBAction method.
When the button is clicked the Action Sheet will be displayed. Change the showActionSheet method in
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Save", nil];
The action sheet is initialized with a cancel and a destructive button. Note the destructive button is always red. The action sheet will be shown in the current view.
To handle the choices presented by your action sheet, you must designate a delegate to handle the button’s action, and the delegate must conform to the UIActionSheetDelegate protocol. Change the interface line in
@interface ViewController () <UIActionSheetDelegate>
Now we can implement the actionSheet:clickedButtonAtIndex delegate method
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
NSLog(@"You have pressed the %@ button", [actionSheet buttonTitleAtIndex:buttonIndex]);
The buttonTitleAtIndex method takes the selected buttonindex and returns the title of the button. Build and Run the project.
You can download the source code of the iOS7ActionSheetTutorial at the ioscreator repository on github.