Change selected segment of UISegmentedControl

这一生的挚爱 提交于 2019-12-24 23:11:42

问题


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?


回答1:


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 .




回答2:


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

Happy Coding :)




回答3:


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?



来源:https://stackoverflow.com/questions/14894322/change-selected-segment-of-uisegmentedcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!