Advertisement
iOS SDK

iOS Quick Tip: Create a Dynamic Action Sheet

by

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.

Related Posts
  • Code
    iOS SDK
    Exploring the Multipeer Connectivity framework: Project Setup78mpi preview image
    As with every major release, iOS 7 includes many new APIs that developers can take advantage of in their applications. In this tutorial, we'll take a look at a brand new framework introduced in iOS 7, the Multipeer Connectivity framework. This framework adds support for discovering, connecting to, and communicating with nearby services, such as iOS devices. In this tutorial, I will show you how to create a simple, multi-player game using this new framework.Read More…
  • Code
    iOS SDK
    Securing and Encrypting Data on iOSPs8e2e preview image@2x
    Whether you're creating a mobile application or a web service, keeping sensitive data secure is important and security has become an essential aspect of every software product. In this tutorial, I will show you how to safely store user credentials using the application's keychain and we'll take a look at encrypting and decrypting user data using a third party library.Read More…
  • Code
    iOS SDK
    Blocks and Table View Cells on iOS94dp7 preview image@2x
    A table view cell doesn't know about the table view it belongs to and that's fine. In fact, that's how it should be. However, people who are new to this concept are often confused by it. For example, if the user taps a button in a table view cell, how do you obtain the index path of the cell so you can fetch the corresponding model? In this tutorial, I'll show you how not to do this, how it's usually done, and how to do this with style and elegance.Read More…
  • Code
    iOS SDK
    Working with NSURLSession: Part 3E548b preview image@2x
    In the previous tutorials, we explored the fundamentals of the NSURLSession API. There is one other feature of the NSURLSession API that we haven't look into yet, that is, out-of-process uploads and downloads. In the next two tutorials, I will show you how to create a very simple podcast client that enables background downloads.Read More…
  • Code
    iOS SDK
    Networking with NSURLSession: Part 2E548b preview image@2x
    In the previous tutorial, I introduced you to NSURLSession. I talked about the advantages it has over NSURLConnection and how to use NSURLSession for simple tasks, such as fetching data from a web service and downloading an image from the web. In this tutorial, we'll take a closer look at the configuration options of NSURLSession and how to cancel and resume a download task. We've got a lot of ground to cover so let's get started.Read More…
  • Code
    iOS SDK
    iOS Succinctly - Hello, iOS!Ios succinctly preview1
    In this article, we’ll introduce the three main design patterns underlying all iOS app development: model-view-controller, delegate objects, and target-action. Read More…