iOS 6.1 – Adding UISegmentedControl to your UINavigationController

In this tutorial, I will show how to add a UISegmentedControl to the navigationBar of your UINavigationController.

First, we need to decide what is going to be in our UISegmentedControl. Let’s use 2 icons from Glyphish Free (http://www.glyphish.com/): 28-star.png and 29-heart.png.

28-star 29-heart

In your Navigation Controller’s rootViewController, setup your UISegmentedControl with our icons:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:[UIImage imageNamed:@"28-star.png"], [UIImage imageNamed:@"29-heart.png"], nil]];


Let’s set the initial selectedSegmentIndex to the star and change the segmentedControlStyle so that it matches nicely with the style of the navigationBar:

segmentedControl.selectedSegmentIndex = 0;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

Now, let’s put our UISegmentedControl into the navigationBar as a navigationItem. We’ll set it as the rightBarButtonItem since the left is usually used to move backwards in the navigationController.

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;

And there you have it! You should have a nice Segmented Control that’s part of your Navigation Bar, like so:

Screen Shot 2013-05-16 at 7.26.58 PM

Hello world!

Welcome to my blog. I’ll be posting tech related things, such as simple code tutorials for programming in iOS along with things like my thoughts about products. Please let me know if there’s something you’d like to see.

- Techie