Programming Segmented Controls


After you slide the segmented control and label onto the page, how do you get them to work together? Here is the code I use to make a three-button UISegmentedControl change the text of a UILabel. (Xcode 3)
________________________
.h file:

@interface SampleViewController : UIViewController
{
IBOutlet UISegmentedControl *controlOne;
IBOutlet UILabel *labelOne;
}

/*
About the naming: I use a common word at the end of each element when they are related; in this case, “One.”
*/

@property (nonatomic, retain) UISegmentedControl *controlOne;
@property (nonatomic, retain) UILabel *labelOne;
– (IBAction)segmentActionToLabelOne:(id)sender;

@end

________________________

After typing in the above, open Interface Builder and drag from File’s Owner to the control and select “controlOne.” Drag from File’s Owner to the label and select “labelOne.”  The control will be acting on the label, so right-click on the control, click on the circle for Value Changed, and left-drag it to File’s Owner and select the IB Action “segmentActionToLabelOne.” Save in IB and return to Xcode.

________________________
.m file:

#import “SampleViewController.h”
@implementation SampleViewController

@synthesize controlOne;
@synthesize labelOne;

#pragma mark –
#pragma mark controlOne Action

/*
If your segmented control uses images in the buttons, or if you need to localize each option, use the following.
/*

– (IBAction)segmentActionToLabelOne:(id)sender
{

switch ([((UISegmentedControl *)sender) selectedSegmentIndex])
{
case 0:
labelOne.text = NSLocalizedString(@”Top”, @”ButtonOption”);
break;
case 1:
labelOne.text = NSLocalizedString(@”Middle”, @”ButtonOption”);
break;
case 2:
labelOne.text = NSLocalizedString(@”Bottom”, @”ButtonOption”);
break;
default: //Make sure this button is checked off as Selected in IB
labelOne.text = NSLocalizedString(@”Middle”, @”ButtonOption”);
break;
}
return;
}

/*
If your control uses text for the buttons, you can use this. It will display the control’s button text in the label.
*/

– (IBAction)segmentActionToLabelOne:(id)sender{
UISegmentedControl *segmentedControlOne = (UISegmentedControl *)sender;
labelOne.text = [segmentedControlOne titleForSegmentAtIndex:[segmentedControlOne selectedSegmentIndex]];
}

-(void)dealloc {
[controlOne release];
[labelOne release];
[super dealloc];
}
@end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s