Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
Classes
CustomSegmentedControls.xcodeproj
CustomSegmentedControls-Info.plist
CustomSegmentedControlsViewController.xib
CustomSegmentedControls_Prefix.pch
MainWindow.xib
README.md
blue-divider.png
bottombarblue.png
bottombarblue_pressed.png
bottombarredfire.png
bottombarredfire_pressed.png
main.m
red-divider.png

README.md

Blog post: http://idevrecipes.com/2010/12/11/custom-segmented-controls

Problem:

UISegmentedControls have only four styles, each with preset heights and colors that you can’t change. How do you create a custom segmented control?

image

Solution:

The Apple docs say:

A UISegmentedControl object is a horizontal control made of multiple segments, each segment functioning as a discrete button

In other words a UISegmentedControl is simply a group of buttons. To create a custom segmented control we can use a simple recipe:

  • Create a custom view that manages a button for each segment.
  • Use a divider image to visually separate segments.
  • Manage the touches on the buttons so when one is selected, the others are deselected.

We need to also figure out the proper appearance of each button but there are at least two ways to make the images for the buttons:

Instead of having the implementation dictate one way, we’ll use a delegate callback so each instance of the custom control can decide how to build the buttons. The delegate also has optional callbacks to get notified when a touch up or touch down occurs on one of the segments. This will be were we takes actions like swapping out views when a user selects a segment.

CustomSegmentedControl.h

@protocol CustomSegmentedControlDelegate

- (UIButton*) buttonFor:(CustomSegmentedControl*)segmentedControl atIndex:(NSUInteger)segmentIndex;

@optional
- (void) touchUpInsideSegmentIndex:(NSUInteger)segmentIndex;
- (void) touchDownAtSegmentIndex:(NSUInteger)segmentIndex;
@end

@interface CustomSegmentedControl : UIView
{
NSObject <CustomSegmentedControlDelegate> *delegate;
NSMutableArray* buttons;
}

@property (nonatomic, retain) NSMutableArray* buttons;

- (id) initWithSegmentCount:(NSUInteger)segmentCount segmentsize:(CGSize)segmentsize dividerImage:(UIImage*)dividerImage tag:(NSInteger)objectTag delegate:(NSObject <CustomSegmentedControlDelegate>*)customSegmentedControlDelegate;

You can see the full source for CustomSegmentedControl.m as well as a sample app showing the custom control in action.

image

Blog post: http://idevrecipes.com/2010/12/11/custom-segmented-controls