Today we will learn how to make a Dropdown option menu in Swift using XCode 6.3 :

Dropdown Menu

Getting started

Open Xcode and create a new project by choosing the Single View Application template. Choose iPhone under “Devices”. Choose Swift as main language.

Templates

Next, you are presented with the page to set many of the important aspects of your project, particularly your “Product Name” and “Language”, which will be Swift, of course.

After you click the “Next” button and then “Create” button, the files for your project are generated and you are probably looking at your AppDelegate.swift file.

Setting up the ViewController

In this tutorial we are going to add a dropdown options menu that has a list of weather the user can choose from. We are not going to use the storyboard instead we will add all the UI elements programatically. First, you need to download some classes for the dropdown menu animation. Download Link

This code is directly provided to you just for your convenience. It contains the IGLDropdownMenu Animation code. Just Drag the folder into your XCode project to get them ready for use. (Note: You also need to add the bridging header file to import IGLDropDown since it written in Obj-C)

Add the following line in the bridging header file:
#import "IGLDropDownMenu.h"

We also need a bunch of images for the menu. Download Here. Once downloaded just drag the .imageset file into your Images.xcasset folder. These image assets contain weather icons.

Open the ViewController.swift file and add IGLDropDownMenuDelegate to view controller as :

class ViewController: UIViewController, IGLDropDownMenuDelegate {

Now let’s declare some variables that we are going to use in future.

var dropDownMenu = IGLDropDownMenu()
    
    var dataImage:NSArray = ["sun.png",
        "clouds.png",
        "snow.png",
        "rain.png",
        "windy.png"]
    var dataTitle:NSArray = ["Sun",
        "Clouds",
        "Snow",
        "Rain",
        "Windy"]

In the code above, we create a IGLDropDownMenu object, dataImage & dataTitle NSArray. The dataImage array stores the name of the images present in the image assets, while the dataTitle stores the menu titles.

We now create a setupInit() function that is fired when the viewDidLoad is done. The code for setupInit is as follows:

func setupInit() {

        var dropdownItems:NSMutableArray = NSMutableArray()
        
        for i in 0...(dataTitle.count-1) {
            
            var item = IGLDropDownItem()
            item.iconImage = UIImage(named: "\(dataImage[i])")
            item.text = "\(dataTitle[i])"
            dropdownItems.addObject(item)
        }
        
        dropDownMenu.menuText = "Choose Weather"
        dropDownMenu.dropDownItems = dropdownItems as [AnyObject]
        dropDownMenu.paddingLeft = 15
        dropDownMenu.frame = CGRectMake((self.view.frame.size.width/2) - 100, 150, 200, 45)
        dropDownMenu.delegate = self
        dropDownMenu.type = IGLDropDownMenuType.Stack
        dropDownMenu.gutterY = 5
        dropDownMenu.itemAnimationDelay = 0.1
        //dropDownMenu.rotate = IGLDropDownMenuRotate.Random //add rotate value for tilting the
        dropDownMenu.reloadView()
        
        var myLabel = UILabel()
        myLabel.text = "SwiftyOS Blog"
        myLabel.textColor = UIColor.whiteColor()
        myLabel.font = UIFont(name: "Helvetica-Neue", size: 17.0)
        myLabel.textAlignment = NSTextAlignment.Center
        myLabel.frame = CGRectMake((self.view.frame.size.width/2) - 100, 75, 200, 25)
        
        self.view.addSubview(myLabel)
        self.view.addSubview(self.dropDownMenu)

    }

I will explain the code written above into parts. First we add a NSMutableArray named dropdownItems. Then we fire a for loop for adding the IGLDropDownItem to the NSMutableArray. We add the text and image to the Item using:

item.iconImage = UIImage(named: "\(dataImage[i])")
item.text = "\(dataTitle[i])"

Furthermore, we use the dropDownMenu object created earlier to setup the dropdown menu. Firstly, we add menuText that stays as the default place holder for the menu. Then, we add the dropdownItems to the menu that contain the title & image name. Next, we add the frame of the menu programmatically using CGRectMake where self.view.frame.size.width/center’s the menu horizontally, y = 150, Width = 200, height = 45.

The dropDownMenu.Type has a variety of options to present the dropdown menu, such as Normal dropdown, Stack, SlidingInBoth, Sliding in from Left, Sliding in from Right. In our case we will use the Stack type menu. We then add the gutterY value that adds space between the list of options. IGLDropDown also provides rotate options for rotating the menu cells to some angle. dropDownMenu.reloadView() adds the properties to the dropdown menu. We then add the UILabel for providing some information as to what the menu contains. At the end we add the menu & label to the parent/Super View using:

self.view.addSubview(myLabel)
self.view.addSubview(self.dropDownMenu)

This setupInit() function will be called from viewDidLoad present in the ViewController.

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        setupInit()
    }

All this time you might be facing an error in your program because you haven’t implemented the necessary functions for the IGLDropDownMenuDelegate . We just need to add the dropDownMenu (_selectedAtIndex: ) function as shown below:

func dropDownMenu(dropDownMenu: IGLDropDownMenu!, selectedItemAtIndex index: Int) {
        
        var item:IGLDropDownItem = dropDownMenu.dropDownItems[index] as! IGLDropDownItem
        println("Selected weather \(item.text)")
        
        
    }

This function is fired when the user taps a single cell in the menu. In our case we just print the name of the item selected in the console using the println() statement.

So to sum up all the code used above, the final ViewController.swift would now look like:

import UIKit

class ViewController: UIViewController, IGLDropDownMenuDelegate {

    var dropDownMenu = IGLDropDownMenu()
    
    var dataImage:NSArray = ["sun.png",
        "clouds.png",
        "snow.png",
        "rain.png",
        "windy.png"]
    var dataTitle:NSArray = ["Sun",
        "Clouds",
        "Snow",
        "Rain",
        "Windy"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        setupInit()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    func setupInit() {

        var dropdownItems:NSMutableArray = NSMutableArray()
        
        for i in 0...(dataTitle.count-1) {
            
            var item = IGLDropDownItem()
            item.iconImage = UIImage(named: "\(dataImage[i])")
            item.text = "\(dataTitle[i])"
            dropdownItems.addObject(item)
        }
        
        dropDownMenu.menuText = "Choose Weather"
        dropDownMenu.dropDownItems = dropdownItems as [AnyObject]
        dropDownMenu.paddingLeft = 15
        dropDownMenu.frame = CGRectMake((self.view.frame.size.width/2) - 100, 150, 200, 45)
        dropDownMenu.delegate = self
        dropDownMenu.type = IGLDropDownMenuType.Stack
        dropDownMenu.gutterY = 5
        dropDownMenu.itemAnimationDelay = 0.1
        //dropDownMenu.rotate = IGLDropDownMenuRotate.Random //add rotate value for tilting the
        dropDownMenu.reloadView()
        
        var myLabel = UILabel()
        myLabel.text = "SwiftyOS Blog"
        myLabel.textColor = UIColor.whiteColor()
        myLabel.font = UIFont(name: "Helvetica-Neue", size: 17.0)
        myLabel.textAlignment = NSTextAlignment.Center
        myLabel.frame = CGRectMake((self.view.frame.size.width/2) - 100, 75, 200, 25)
        
        self.view.addSubview(myLabel)
        self.view.addSubview(self.dropDownMenu)

    }
    
    func dropDownMenu(dropDownMenu: IGLDropDownMenu!, selectedItemAtIndex index: Int) {
        
        var item:IGLDropDownItem = dropDownMenu.dropDownItems[index] as! IGLDropDownItem
        println("Selected weather \(item.text)")
        
        
    }

}


That’s pretty much it for this tutorial, next step is to build & run the app.

Running the App

So now you run the app with the big “Play” button in the top left of Xcode.  You then need to set what device to run the app on.  You can select a physical device (if you have a paid developer license).  Otherwise, or even just for simpler testing, you can run it in the simulator.  Choose the simulated device to run it on from the same menu.

Then wait a bit while the simulator loads.  Mine took about 30 seconds to load.

Here is the source code on Github for the tutorial above !

I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don’t hesitate to contact me on Twitter @swifty_os, and I’ll see what I can do.  As I said the second part of this tutorial will add Dribbble shots detail view with user comments & user profile screens. Thanks!