If you want to present a small selection of options to the user, you can achieve this with an UIActionSheet. The action sheet will slide in front of the view and will present the options as clickable buttons. In this tutorial we will give the user the option to rate the app.
This tutorial targets iOS 6 and earlier. Click here for the iOS 7 version of displaying a menu with an UIActionSheet.
Open Xcode and create a new Single View Application. For product name, use ActionSheetDemo 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, and that the Use Storyboards is deselected and Use Automatic Reference Counting checkboxes are selected (Unit Tests will not be necessary for this project).
Go to viewController.xib and drag a label to the view. Give the label the text "Rate this app" and in the Attributes inspector choose the center alignment button. Also drag a button to the view and name this button Rate. The view should look like this
In viewController.m change the interface section to
@interface ViewController ()
@property (nonatomic, weak) IBOutlet UILabel *label;
Go back to the ViewController.xib and make the following connections:
- Rate this app label -> rateLabel
- displayActionSheet -> Rate Button
in ViewController.m, implement the displayActionSheet method
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Rate this App" delegate:self cancelButtonTitle:@"Cancel Button" destructiveButtonTitle:nil otherButtonTitles:@"Rate 1 Star", @"Rate 2 Stars", @"Rate 3 Starts", @"Rate 4 Stars", @"Rate 5 Stars", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault; [actionSheet showInView:self.view];
The action sheet is initialised with a title of "Rate this App", 5 rate buttons and also a Cancel button. With the showinView method the action sheet is originated from the current main view.
To update the label button we need to conform the viewController to the UIActionSheetDelegate. Update the @interface line to
[objc]@interface ViewController () [/objc]
Implement the actionsheet:clickedButtonAtIndex method which is part of the UIActionSheetDelegate protocol.
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
self.rateLabel.text = @"You've rated 1 star.";
self.rateLabel.text = @"You've rated 2 stars.";
self.rateLabel.text = @"You've rated 3 stars.";
case 3: self.rateLabel.text = @"You've rated 4 stars.";
case 4: self.rateLabel.text = @"You've rated 5 stars.";
case 5: self.rateLabel.text = @"You haven't rate this app yet.";
Every button has a buttonindex, so in the case statement the rateLabel is updated.
Build And Run, and rate this app.
You can download the source code of the ActionSheetDemo at the ioscreator repository on github.