Change UISegmentedControl selected index or value programmatically

Mrwolfy picture Mrwolfy · Jan 24, 2013 · Viewed 40k times · Source

I have a UISegmentedControl with two segments (index: 0 and 1) that I am trying to reset programmatically to 0. When I run the command below it does not reset the segment index to 0 as expected. Instead it highlights segment indexed 1.

    [seg setSelectedSegmentIndex:0];

Oddly when I log the selected segment, it returns 0.

    NSLog(@"seg setSelectedSegmentIndex %d", seg.selectedSegmentIndex); 

Also oddly, after running setSelectedSegmentIndex:0 I cannot reselect segment 0 manually by touch, it seems to be locked to segment 1, until I tap 1 wherein it works as normal.

Here is the setup for the button:

    itemArray = [NSMutableArray arrayWithObjects: @"Zero", @"One", nil];
    seg = [[UISegmentedControl alloc] initWithItems:itemArray];
    [seg setFrame:segRect];
    seg.segmentedControlStyle = UISegmentedControlStyleBar;
    seg.momentary = NO;
    [seg addTarget:self action:@selector(someAction:) forControlEvents: UIControlEventValueChanged];
    [mainView addSubview:seg];

NOTE: To restate what I was trying to accomplish with this question: I want to set a UISegmentedControl's selected index via a variable dynamically, get the appropriate visual feedback, and check the selected index in a method, to make something happen depending on the selected index. See my answer below for a solution.

Answer

Krishnan8190 picture Krishnan8190 · Jan 24, 2013

Change in viewDidLoad:

[seg setSelectedSegmentIndex:index];

you change use the index value as your wish.