Problem:
You can select one of the simple and easy-to-understand options.
Create a uisegmentedcontrol instance to initialize a control:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; NSArray *segments = [[NSArray alloc]initWithObjects: @"iPhone", @"iPad", @"iPod", @"iMac", nil]; _mySegmentControl = [[UISegmentedControl alloc]initWithItems:segments]; _mySegmentControl.center = self.view.center; [self.view addSubview:_mySegmentControl];}
Now, how do we know that the user has selected an option? The answer is simple. Just like uiswitch and uislider, use addtarget: Action: forcontrolevents: to add a target. you need to pass the uicontroleventvaluechanged value to the forcontrolevents parameter because this parameter triggers the event when you select an option in the control.
[_mySegmentControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
//segment选项变化时调用方法- (void)segmentChanged:(UISegmentedControl *)paramSender{ if ([paramSender isEqual:_mySegmentControl]) { NSInteger selectedSegmentIndex = [paramSender selectedSegmentIndex]; NSString *selectedSegmentText = [paramSender titleForSegmentAtIndex:selectedSegmentIndex]; NSLog(@"Segment %ld with %@ text is selected", (long)selectedSegmentIndex,selectedSegmentText); }}
If you want to change this option back to the original state (as if it was not selected) after you select an option, set the momentary attribute to yes.
_mySegmentControl.momentary = YES;
A very flexible feature of the segment control is that it can display images. To display an image, use initwithobjects: the initialization method transmits the image, character, and image as parameters at the same time.
NSArray *segments = [[NSArray alloc] initWithObjects: @"iPhone",[UIImage imageNamed:@"iPad.png"],@"iPod",@"iMac", nil];self.mySegmentedControl = [[UISegmentedControl alloc] initWithItems:segments];
Ui: uisegmentedcontrol: simple option grouping and customization