Picking a choice from a group or set of values using UISegmentedControl


/ Published in: Objective C

The UISegmentedControl consists of a horizontal control divided into segments. Segmented controls are useful for allowing users to pick from a group or set of values.

Each segment functions as its own button. By default, selecting a segment will deselect the others in the control (much as a radio button does in HTML). You can alter this behavior by setting the "momentary" property.


Copy this code and paste it in your HTML
  1. - (void)segmentClick:(id)sender
  2. {
  3. NSLog(@"you selected segment %d",[sender selectedSegmentIndex]);
  4. }
  5.  
  6. - (void)viewDidLoad {
  7.  
  8. [super viewDidLoad];
  9.  
  10. NSArray *arrSegments = [[NSArray alloc] initWithObjects:
  11. [NSString stringWithString:@"0"],
  12. [NSString stringWithString:@"1"],
  13. [NSString stringWithString:@"2"],nil];
  14.  
  15. UISegmentedControl *mySegment = [[UISegmentedControl alloc] initWithItems:arrSegments];
  16.  
  17. CGRect segmentRect = CGRectMake(10,50,300,40);
  18. [mySegment setFrame:segmentRect];
  19.  
  20. [mySegment addTarget:self action:@selector(segmentClick:) forControlEvents:UIControlEventValueChanged];
  21.  
  22. [mySegment setSegmentedControlStyle:UISegmentedControlStyleBar];
  23. [mySegment setTintColor:[UIColor darkGrayColor]];
  24. // mySegment.momentary = YES; // allow multiple multiple selection
  25.  
  26. //select first item
  27. [mySegment setSelectedSegmentIndex:0];
  28.  
  29. //change a segment size
  30. [mySegment setWidth:120.0 forSegmentAtIndex:1];
  31.  
  32. //add a new segment
  33. [mySegment insertSegmentWithTitle:@"new" atIndex:2 animated:YES];
  34.  
  35. //add segment to main view
  36. [self.view addSubview:mySegment];
  37.  
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.