Skip to content

A 1.8. Grouping Compact Options with UISegmentedControl

rayastar edited this page Feb 7, 2015 · 1 revision

A segmented control is a UI component that allows you to display, in a compact UI, a series of options for the user to choose from. To show a segmented control, create an instance of UISegmentedControl. Let’s start with our view controller’s .m file:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UISegmentedControl *mySegmentedControl;
@end

And create the segmented control in the viewDidLoad method of your view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *segments = [[NSArray alloc] initWithObjects:
                         @"iPhone",
                         @"iPad",
                         @"iPod",
                         @"iMac", nil];

    self.mySegmentedControl = [[UISegmentedControl alloc]
                               initWithItems:segments];
    self.mySegmentedControl.center = self.view.center;
    [self.view addSubview:self.mySegmentedControl];
}

Now the question is, how do you recognize when the user selects a new option in a segmented control? The answer is simple. Just as with a UISwitch or a UISlider, use the addTarget:action:forControlEvents: method of the segmented control to add a target to it. Provide the value of UIControlEventValueChanged for the forControlE vents parameter, because that is the event that gets fired when the user selects a new option in a segmented control:

- (void) segmentChanged:(UISegmentedControl *)paramSender
{
    if ([paramSender isEqual:self.mySegmentedControl])
    {
        NSInteger selectedSegmentIndex = [paramSender selectedSegmentIndex];
        NSString  *selectedSegmentText =
        [paramSender titleForSegmentAtIndex:selectedSegmentIndex];
        NSLog(@"Segment %ld with %@ text is selected", (long)selectedSegmentIndex, selectedSegmentText);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *segments = [[NSArray alloc] initWithObjects:
                         @"iPhone",
                         @"iPad",
                         @"iPod",
                         @"iMac", nil];

    self.mySegmentedControl = [[UISegmentedControl alloc]
                               initWithItems:segments];
    self.mySegmentedControl.center = self.view.center;
    [self.view addSubview:self.mySegmentedControl];
     [self.mySegmentedControl addTarget:self action:@selector(segmentChanged:)
                       forControlEvents:UIControlEventValueChanged];

}

If you want the user to be able to select an option but you would like the button for that option to bounce back to its original shape once it has been selected (just like a normal button that bounces back up once it is tapped), you need to set the momentary property of the segmented control to YES:

self.mySegmentedControl.momentary = YES;
Clone this wiki locally