Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

iOS Quick Tip: Create a Dynamic Action Sheet

$
0
0

Welcome to this entry-level quick tip about working with action sheets. In this tutorial, you will learn how to create a simple action sheet dynamically using content from an array. This technique will allow you to determine how many buttons to place on the action sheet at run-time as opposed to compile-time. A handy technique to have!

We will create a simple application in this tutorial that will show us a list of fruits in an action sheet. If you select a fruit, a label’s text will be updated with the selected fruit.


Step 1: Creating the Project

Open Xcode and select “Create a new Xcode project”. Select “Single View Application” and click “next”. Enter a name for your project (I called mine “Fruits”), make sure you select iPhone for the Devices and select the “Use Storyboards” and “Use Automatic Reference Counting” checkboxes. After that click, “next” and choose a place to save your project before clicking “create”.

    Create Project

Step 2: Setting Supported Orientations

We only want to use this application in portrait mode, so go to the Supported Interface Orientations section and deselect the landscape orientations.

    Supported Orientations

Step 3: Creating the Interface

Open the Storyboard and drag a label from the Object Library to the View Controller. Place it at the top of the View Controller and make sure it’s centered and it’s 280 pixels wide. Open the Attributes Inspector and change the Alignment to center. At last, delete the text.

Next, drag a Button from the Object Library to the View Controller and place it just below the label. Double click on its title and change it to “Fruits”.

    Interface

Step 4: Making the IBOutlet Connections

Open ViewController.m and modify the code to read as follows:

#import "ViewController.h"
@interface ViewController () <UIActionSheetDelegate>
@property(nonatomic, weak)   IBOutlet UILabel *fruitLabel;
@property(nonatomic, strong) NSMutableArray *fruits;
- (IBAction)showFruits:(id)sender;
@end

Here we create an outlet for our label, a mutable array to store our fruits, and we create an action to show the action sheet. We also added the UIActionSheetDelegate, so we can update the label when you select a fruit from the action sheet. Note that all of this was done in the class extension because none of these properties or methods need to be exposed to an outside class.

Now that we have created the outlet and action, we only need to connect them with the corresponding elements. Open the Storyboard and connect the fruitsLabel outlet with the label and the showFruits: action with the button. Select Touch Up Inside as the control event for the button.


Step 5: Create a List of Fruits

Open ViewController.m and create the following initializer method:

-(id) initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        self.fruits = [[NSMutableArray alloc] initWithObjects:@"Apple", @"Orange", @"Banana", @"Strawberry", @"Peach",nil];
    }
    return self;
}

Here we create our fruits array and store some fruits within it.


Step 6: Show the List

Add the following code below the didReceiveMemoryWarning method:

- (IBAction)showFruits:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select a fruit"
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    for (NSString *fruit in self.fruits) {
        [actionSheet addButtonWithTitle:fruit];
    }
    actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
    [actionSheet showInView:self.view];
}

We first create an action sheet, like you would normally do. We give it a title and a delegate, but we don’t add any buttons, not even a cancel button. If we were to add a cancel button here, and all the other buttons later, the cancel button would be on top of the list, instead of at the bottom.

Next, we use a fast enumeration loop to go through all the fruits stored in the fruits array created earlier. In that for loop, we add buttons for all the fruits to the action sheet. After the for loop, we add a cancel button to the action sheet. As you can see, we do that by adding a button with the title “Cancel” to the cancelButtonIndex. This way the action sheet knows that the Cancel button should be at the bottom of the list. At last, we show the action sheet the normal way.


Step 7: Update the Fruits Label

Add the following action sheet delegate protocol method below the showFruits: action:

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        self.fruitLabel.text = [self.fruits objectAtIndex:buttonIndex];
    }
}

This delegate method gets called when you press a button from the action sheet. First, we check if the button pressed is for a fruit or the cancel button. We do that by comparing the selected button index with the cancel button index. If the selected button is for a fruit, we update the label with the selected fruit.


Wrap Up

Thanks for reading this quick tip about creating an action sheet with items from an array. I hope you found it useful! If you have questions or comment on this quick tip, leave them in the comments section below.


Viewing all articles
Browse latest Browse all 1836

Trending Articles