user1354743
user1354743

Reputation: 417

Change selected segment of UISegmentedControl

I have a UISegmentedControl in my ModeViewController

ModeViewController.h:

@property (weak, nonatomic) IBOutlet UISegmentedControl *Segment;
- (IBAction)switchMode:(id)sender;

ModeViewController.m:

- (IBAction)switchMode:(id)sender {
    //I Tried this way    
    UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
    _Segment.selectedSegmentIndex = segmentedControl.selectedSegmentIndex;


//or this way
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
[_Segment setSelectedSegmentIndex:selectedSegment];

}

But as soon as I change to ViewController and come back it will only display the default selected Segment! Any idea?

Upvotes: 0

Views: 4012

Answers (3)

Lithu T.V
Lithu T.V

Reputation: 20021

Problem

The problem here is that whan a Viewcontroller is presented modally the properties inside it has only the lifetime till it is dismissed.

Check your code there will be an instantiation of the viewcontroller which gives you a new instance and in this new instance the segment control from the nib set value will be shown(or whatever you set in viewDidload or ViewWillAppear methods

Solution

The solution is to store the value somewhere where it is possible to retrive and set in viewDelegates as

  [self.segment setSelectedSegmentIndex:storedIndex];

For this purpose of storing there are different options

  1. Global variable in appDelegate
  2. NSUserDefaults
  3. CoreData
  4. Sqlite
  5. Plist
  6. TextFile

The easiest one is the first but if you are implementing any of this already a field for this is a considerable option.

Upvotes: 2

Baby Groot
Baby Groot

Reputation: 4279

You need to make that variable selectedSegment global in your app. you can define it in AppDelegate

iPhone, how do I App Delegate variable which can be used like global variables?

Upvotes: 1

V-Xtreme
V-Xtreme

Reputation: 7333

After you change view controller and you come back the viewDidLoad method called again thats why you are seeing the default selected index. The way to overcome this is store the selected the selected index into some app delegate property or you can create singleton class for the better design to preserve the state .And in your viewDidLoadMethod .

-viewDidLoad
{
  AppDelegate *delegate=[[UIApplication sharedAppliection]delegate];
  [_Segment setSelectedSegmentIndex:delegate.selectedIndex];
}

This wil work for you .

Upvotes: 2

Related Questions