Thursday 2 February 2012

Simple Menus and Messages with UIActionSheet


If you need to create a quick menu or present a user with a short message, you may want to consider a UIActionSheet as an option. This control will slide up from the bottom of the screen, and offers a number of easily configurable options.
The code in the interface definition below creates an actionsheet (if you prefer, you can accomplish the same using Interface Builder to layout and define a UIActionSheet). Notice there is a delegate required if you define multiple buttons on the sheet and need to determine which was tapped:
@interface SandboxViewController : UIViewController <UIActionSheetDelegate>
{
  ...
  UIActionSheet *sheet;
}
@end
At some point in your code you can create a sheet as follows:
sheet = [[UIActionSheet alloc] initWithTitle:@"Select Belgian Beer Style"
                                      delegate:self
                             cancelButtonTitle:@"Cancel"
                       destructiveButtonTitle:nil
                            otherButtonTitles:@"Dubble", @"Lambic", @"Quadrupel", @"Strong Dark Ale", @"Tripel", nil];
 
  // Show the sheet
  [sheet showInView:self.view];
  [sheet release];
Here is another variation:
sheet = [[UIActionSheet alloc] initWithTitle:@"Select Account to Delete"
                                      delegate:self
                             cancelButtonTitle:@"Cancel"
                        destructiveButtonTitle:@"Delete All Accounts"
                             otherButtonTitles:@"Checking", @"Savings", @"Money Market", nil];
  // Show the sheet
  [sheet showInView:self.view];
  [sheet release];
The screenshots below show each of the above sheets and how they look on the simulator:
To determine which button was selected, implement the method shown below:
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
  NSLog(@"Button %d", buttonIndex);
}
One additional way to use an actionsheet is to present information to a user, in this case, you fill in the title and just one button:
sheet = [[UIActionSheet alloc] initWithTitle:@"Lorem ipsum dolor...."
                                      delegate:self
                             cancelButtonTitle:nil
                        destructiveButtonTitle:nil
                             otherButtonTitles:@"Got it." ,nil];
 
  // Show the sheet
  [sheet showInView:self.view];
  [sheet release];

0 comments:

Post a Comment

 

Copyright @ 2013 PakTechClub.