iOS Development Tutorial Series: PickerViews & More

By
On March 28, 2011

Hello, and welcome to another iOS Development tutorial. Today we are going to learn about UIPickerViews and how to switch viewcontrollers (I’ll explain what that is later).

I’ll start off by explaining that picker views work fairly the same way as table views, so if you did the last tutorial then you should have no problem understanding this one.

In the last tutorial I took a poll about whether we should use Xcode 4 or Xcode 3 in the tutorials and it looks like Xcode 4 won by a long shot. So, we will be using Xcode 4 in our tutorials from now on. I will try to explain where things are in Xcode 4 and how things work, but be patient, as I am learning as well. If you are not a part of the iPhone developer program, you download Xcode 4 from the Mac App Store for $5.

By now you should have downloaded Xcode 4 and installed it.

Lets get to the tutorial.

1. Create a new view-based project name “Picker”

 

As you can see Xcode 4 is completely redesigned. Everything is now in one window, rather the multiple windows that was in Xcode 3. For example, in the interface builder application you had four different windows just to build your view. In Xcode 4 everything is in one window and is much easier to build your views and write your code. We will explore more of Xcode 4 later, but for now that will do.

2. Go to the header file (PickerViewController.h) and lets create come new actions and IBOutlets. In the header file, type:

IBOutlet UIPickerView *pickerView;
NSArray *pickerViewArray;
@property (nonatomic, retain) NSArray *pickerViewArray;
-(IBAction)selectedRow;

Since we are going to be using a picker view in our application our viewcontroller must conform to the UIPickerView protocols. This works the same way as the protocols for a table view.

3. In the @interface line type:

These two lines of code make our viewcontroller conform to the UIPickerViewDelegate protocol and the UIPickerViewDataSource protocol.

Now that we have our action, outlet, and property declared, we need to synthesize the property in the implementation file.

4. In the implementation file type:

@synthesize pickerViewArray;

Since picker views work very similar to the way table views work, we need to implement the methods that are required for the picker view to function.

5. Copy this code into the implementation file:

– (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
– (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [pickerViewArray count];
}
– (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [self.pickerViewArray objectAtIndex:row];
}

In the first method we are saying that we want one component in our picker view. You may ask what a component is. Well, if you go to the clock application that comes stock on the iPhone, and add an alarm clock you will see that the picker view has 3 components.

In the second method we are saying that we want the number of rows in the picker view to the be the number of objects in our NSArray. You should already understand this since we covered it in the last tutorial.

In the third method we are populating the picker view with the contents of the NSArray. This works the same way as the table view methods work. We are setting the value of the row in the picker to the object in the NSArray that is at the same index as the picker view is currently selected.

6. Below our new methods type:

-(IBAction)selectedRow {
int selectedIndex = [pickerView selectedRowInComponent:0];
NSString *message = [NSString stringWithFormat:@”You selected: %@”,[pickerViewArray objectAtIndex:selectedIndex]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Alert” message:message delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];
[alert show];
[alert release];
}

In our IBAction we are creating an integer and setting the value to the selected index of the picker view. Then we create an NSString and give it some generic text (“You selected”) and then put the value of the NSArray that is at the same index as our picker view, using our integer that we created. We then create an alert and display it to the user (you should already know how to do this as well).

Ok, that’s cool, but if we were to run the application our picker view would be empty. Why? Because our array has no data. We must load our picker view with some new data.

7. Uncomment the “viewDidLoad” method and type this code in it:

– (void)viewDidLoad
{
NSArray *arrayToLoadPicker = [[NSArray alloc] initWithObjects:@”iPhone”,@”iPad”,@”iPod”,@”iMac”,@”MacBook”,@”MacBook Pro”, nil];
self.pickerViewArray = arrayToLoadPicker;
[arrayToLoadPicker release];

[super viewDidLoad];
}

Here we are creating an NSArray and giving a list of strings. Then we set our main NSArray equal to the one we just created.

Now we have our code finished, but we haven’t linked our code to our interface yet.

8. Single click the PickerViewController.xib and create our interface

As you can see, interface builder is now integrated with Xcode and is much easier to design your interfaces with.

Using the far right button under the view section in the top right of Xcode you open the view on the right side of Xocde. For example,

Down in the bottom right you are given a window with all of the objects that you can place on your main view, it works similarly to the old interface, just a little more enclosed in one window.

Drag all the objects onto the view to make your interface look similar to this one:

You should now have your interface built. Now we need to plug our outlets and actions to our objects.

9. Select the button on your view and then select connections tab right above the objects view and drag the plus button beside “Touch Up Inside” to the files owner to link the button to our IBAction.


10. Now select the files owner and link the pickerView outlet to the picker view.
11. Now select the picker view and drag the data source and the delegate to the files owner so that the picker view will know to look for the methods to populate the picker view.

We’re done! Build and Run your application and watch it in action.

We aren’t done yet. Now we want to be able to load a new view controller onto our window, so lets get started with that.

12. Right click on the “Picker” folder and select “New File”

Now you will be presented with a window that will allow you to select the different types of files you can add to your project. For this tutorial we are going to use the UIViewController Subclass template.

13. Select the UIViewController Subclass and the hit Next

14. Now give it a name of “SecondViewController” and then hit Next

As you can see this added three new files to your project. It added a header file, implementation file, and interface builder file to your project.

Now that we have a new viewcontroller we need to give it some code so that it doesn’t just load a blank page.

15. Go to the SecondViewController headfile (SecondViewController.h) and add a new IBAction called “goBack”

Now that we have our IBAction declared, we need to give this action some code.

16. In the SecondViewController.m type:

-(IBAction)goBack {
[self dismissModalViewControllerAnimated:YES];
}

This code is pretty self explanatory. It closes the viewcontroller that is currently loaded and animates it closing.

Now that we have our code to close the viewcontroller, we need the code to open the viewcontroller.

17. In the PickerViewController.h file we need to import our new viewcontroller so that we will have access to load the viewcontroller we just created. In PickerViewController.h type:

#import “SecondViewController.h”

Now that we have access to the SecondViewController, we need to write the code that will load that viewcontroller.

18. Below our selectedRow method, create a new one called switchControllers.

19. Copy this code into the PickerViewController.m file:

-(IBAction)switchControllers {

SecondViewController *viewcontroller = [[SecondViewController alloc] initWithNibName:@”SecondViewController” bundle:nil];

[self presentModalViewController:viewcontroller animated:YES];

[viewcontroller release];

}

Lets start with the first line of code… The first line is creating an instance of the SecondViewController (we are only able to do this because we imported the SecondViewController into our viewcontroller).

In the second line we are presenting our viewcontroller and saying yes to being animated. You can play with the animation effect if you want to. If you say NO, rather than YES it will present the viewcontroller with no animation.

In the last line we are releasing the instance of the SecondViewController we created.

We now have finished coding our project, but we haven’t designed the view for the SecondViewController.

20. Click the SecondViewController.xib and design your view to look similar to this one:

21. Now link the goBack IBAction to the Back button.

22. Now back to the PickerViewControlller.xib and put a new button on your view called “Next ViewController”

23. We’re almost done, just link of the IBAction to the button.

We’re done! Build and run you project to see your hard work.

We’ve now completed our first Xcode 4 project!

We’ve learned a couple of things thoughout this tutorial… We’ve learned how to use a picker view (and that they work simillarly to table views) and how to present a different viewcontroller’s view on your window.

If you  have any questions feel free to ask!

We will be using Xcode 4 from now on.

See you next tutorial! 🙂

You can download the project here.

If you enjoy my tutorials, you can support me by buying my app from the App Store (here). Thanks!