I have been creating my application in a primarily programatic approach and have been attempting to add a UISegmentedControl to the UINavigationControl Toolbar. I have the view created and shown and an action for when the UISegmentedControl is selected. The issue is that at any point I call selectedSegmentIndex, it returns a null value. Any ideas why?
NSArray *segmentArray = [[NSArray alloc] initWithObjects:@"Factory Laods", @"User Loads", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: segmentArray];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[segmentedControl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *segmentedButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *array = [[NSArray alloc] initWithObjects:flexibleSpace, segmentedButton, flexibleSpace, nil];
[self setToolbarItems:array];
——– action method ————
- (void) action:(id)sender {
UISegmentedControl *segment = (UISegmentedControl *) sender;
NSLog(@"Button %@", [segment selectedSegmentIndex]);
}
The flexibleSpace object is a UIBarButtonItem initialized to be just a flexible space to center out the UISegmentedControl. After this item is added I can add an NSLog statement and identify a null value for the selectedSegmentIndex and it’s also null when the event is triggered and checked in the action method. Thanks!
Your action method might be helpful to see but in your code above, you’ve included
segmentedButtonto the array which you set the toolbar items with but you created it assegmentedControl.Could be a typo, or your issue!