Implementing A Stylized UISegmentedControl
I’m currently in the process of implementing a new UI theme for the iPad application that I’m working on. Several of the mockups sent over by the designer include a stylized UISegmented control:

UISegmented Control Mockup
The custom green and gold backgrounds are simple to implement if you’re targeting iOS 5 or newer. Starting in iOS 5, Apple implemented several new methods to customize the appearance of UISegmentedControls. You can a list of the appearance methods in Apple’s Documentation.
The tricky part was how to display the gold arrow indicator below the selected segment. I needed to be able to use this UI style in several places within the app so I couldn’t simply include the arrow within a fixed width background image. The solution I came up with was to add a method that fires when the selected segment index changes. In the method I move the arrow graphic from the previously selected segment to the new one and then center it.
- (void)selectedSegmentChanged:(id)sender { // Remove the arrow from its current view [self.segmentArrow removeFromSuperview]; // The segment items are added in reverse order of their index so we need to flip the selected index NSInteger viewIndex = self.numberOfSegments - 1 - self.selectedSegmentIndex; // Get a reference to the segment and position the arrow outside of its frame UIView *segmentView = [self.subviews objectAtIndex:viewIndex]; [segmentView addSubview:self.segmentArrow]; self.segmentArrow.center = CGPointMake(segmentView.frame.size.width / 2, kStyledSegmentedControlHeight + self.segmentArrow.frame.size.height / 2); }
One thing to note here is that when you get a reference to an individual segment from the UISegmentedControl’s subviews is that the segments are stored in reverse order.
I encapsulated all of the UI customizations into a subclass of UISegmentedControl so that I could easily reuse them across my application. I’ve put together a simple example project on Github to demonstrate how to use the subclass: KFSegmentedControlExample
Hopefully someone else will find this useful in their own project!
Discussion Closed