Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default segment in UISegmentedControl

I have an app that has two viewcontrollers Viewcontroller and OptionsViewController. Viewcontroller is the initial viewcontroller then if I click a button I have a modal segue to optionsviewcontroller.

There in optionsviewcontroller I have I UISegmented viewcontroller created from the storyboard which is linked to an outlet (UnitsSegmentedControl) and I want to be able to tell the segmented control which segment should be selected by default when OptionsViewController loads.

In my Viewcontroller I wrote a method:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    OptionsViewController *ovc=[segue destinationViewController];
    ovc.delegate=self;
    [ovc.UnitsSegmentedControl setSelectedSegmentIndex:1];
}

the thing is when OptionsViewController loads the view the selected index is 0 as by default. I don't get any error message or something.

I'm using Xcode 4.2. I think It might be some option I can change in storyboard to make the UISegmentedControl to be able to set default selected index. I don't know what else could be causing that.

EDIT: I figured out that if I write :

[ovc.UnitsSegmentedControl setSelectedSegmentIndex:1];

inside OptionsViewController method viewdidload everything works fine. Why am I not able to do it from the prepare for segue method?

like image 985
Mppl Avatar asked Jan 14 '12 12:01

Mppl


2 Answers

The segmented control does not exist until the OptionsViewController is loaded which is why you cannot set the selected segment in the prepareForSegue method of you ViewController. Review the UISegmentedControl Class Reference reveals that there is no way to set a default state:

"The default value is UISegmentedControlNoSegment (no segment selected) until the user touches a segment. Set this property to -1 to turn off the current selection. UISegmentedControl ignores this property when the control is in momentary mode. When the user touches a segment to change the selection, the control event UIControlEventValueChanged is generated; if the segmented control is set up to respond to this control event, it sends a action message to its target."

Setting the selectedSegmentIndex in the viewDidLoad method of your OptionsViewController is the correct way to set a default value the view controller.

like image 114
T.J. Avatar answered Nov 08 '22 09:11

T.J.


Just use this code if you want to do it programmatically

segmentControl.selectedSegmentIndex=-1;

If you want to set it from nib then in interface builder just uncheck selected property of index

like image 29
Desert Rose Avatar answered Nov 08 '22 07:11

Desert Rose