Programmatically Setting a UISegmentedControl From IB

I added my UISegmentedControl from Interface Builder easily enough. I just wanted needed to change it to the needs of the data.

BUT…since I added it in interface builder I cannot use initWithArray: so I need to connect it up in Xcode, clear it out and then add in what I need. Then we’ll update the app when the UISegmentedControl is updated.

@interface TopicViewController : UIViewController
 
@property (strong, nonatomic) IBOutlet UIButton *filterButton;
@property (strong, nonatomic) IBOutlet UISegmentedControl *filterSegmented;
 
-(void)segmentChanged:(id)sender;


Then I connect up the UISegmentedControl in Interface Builder.
Since it is already alloc’ed by IB we need to clean it out and then add in new items. Here’s the code in my – (void)viewDidLoad

[filterSegmented removeAllSegments];
        int i=0;
        for (NSDictionary *indexDict in indexLevel){
            [filterInfoTmp addObject:filterLevelDict];
            [filterSegmented insertSegmentWithTitle:[NSString stringWithFormat:@"%@",[indexDict objectForKey:@"title"]] atIndex:i animated:NO];
}

First since I know it is already initialized I ‘removeAllSegments’. Then in my loop through my data I insertSegmentWithTitle and I disregard the ‘animated:’ since this is the first thing the user will see anyway. Here is what it looks like running:
Now I want to change the button to reflect what is selected in my UISegmentedControl. We’ll add this code right after the last stuff (in ‘viewDidLoad’):

        [filterSegmented addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];

The delegate target is this object and we want to call the method ‘segmentChanged:(id)sender;’ when the value changes. My data is kept in an NSArray of NSDictionaries, which is very helpful. That is what ‘*theInfo’ is. Here’s that method and the end result:

-(void)segmentChanged:(id)sender{
    //Change the button text when the segmented control changes
        int theSegmentIndex = [filterSegmented selectedSegmentIndex];
        NSDictionary *theInfo = [filterInfo objectAtIndex:theSegmentIndex];
        [filterButton setTitle: [NSString stringWithFormat:@"%@ (%@) >",[theInfo objectForKey:@"title"],[theInfo objectForKey:@"count"]] forState:UIControlStateNormal];
}

Final implementation. Now when one of the segmented controls is clicked it changes the text on the button!