This is similar to the current answers, but cleared up a bit for iOS 8 devices.
NSArray *itemArray = [NSArray arrayWithObjects: @"Uno", @"Dos", @"Tres", nil]; UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray]; segmentedControl.frame = CGRectMake(35, 200, 250, 50); [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged]; segmentedControl.selectedSegmentIndex = 1; [self.view addSubview:segmentedControl];
- Create an array to store values โโfor the segment
- Initialize a segment using an array
- Assign it the location on the screen and the size of the control
- Point it to a method that is called when the user interacts with it.
- Choose the default value (in this case, Dos)
- Put it on the main view
Then create a segmentAction method that is called when the user changes the value
- (void)segmentAction:(UISegmentedControl *)segment { switch (segment.selectedSegmentIndex) { case 0: // Uno break; case 1: // Dos break; case 2: // Tres break; default: break; } }
I just prefer the switch statement because it is cleaner to watch. You can improve it by creating an enumeration and using the values โโin it for parameters (optionUno, optionDos, optionTres) instead of 0,1,2.
CodeBender Nov 26 '14 at 18:17 2014-11-26 18:17
source share