How to get input from a segmented control

I am trying to get a user selection from a segmented control and then save it in NSUserDefaults, that is, if the first segment is selected, it saves int "1" in NSUserDefaults, but if the second segment is selected, it saves int "2" in NSUserDefaults.

+4
source share
4 answers

The easiest way is to use binding. Bind the selected index of the control to the default shared user controller and set the model key path to the preference key that you want to use.

Edit to add . I see that you did not specify Mac or iOS. If it's a Mac, binding is definitely an easy way, whereas binding is not available on iOS.

The fact that segmented control values ​​start at 0 is unimportant. You can snap the selected tag, not the selected index, and then use whatever tags you want.

+3
source
- (IBAction)totalAction:(id)sender { toggleNav = sender; // this is your segmented control if ([toggleNav selectedSegmentIndex] == 0) { NSlog(@"i am here"); } else if ([toggleNav selectedSegmentIndex] == 1) { NSlog(@"i am here"); } } 
+8
source

Do not listen to the guy above. The first thing you should know is that the UISegmentedControl starts from scratch. So, the first bar is 0, the second is 1, the third is 2, etc. .... If you want to start from zero, just add it to the integer after receiving the value. (See below) To get its value when it changes, connect the IBAction method and connect it to your UISegmentedControl. Do the action with valueChanged, not touchUpInside. Then, as part of your IBAction method, let's say it's called theMethod, use this code.

 -(IBAction)theMethod { int theInteger; theInteger = [segmentedController selectedSegmentIndex];//segmentedController is the name of your UISegmentedController. //theInteger ++; //adds 1 to the integer so as to start the numbering at 1 instead of 0 like I have explained up above. 

Then you can save the integer using NSUserDefaults.

Please note: you will need to convert the integer to NSNumber if you want to save it, because you cannot save integers or variables, you can only save objects. For this, I would use the following:

 NSNumber *myNumber = [NSNumber numberWithInt:theInteger]; 
+1
source

if you work with iOS, you can add the following to segmentedcontrol

  [yourSegmentedControl addTarget:self action:@selector(valueChanged:) forControlEvents: UIControlEventValueChanged]; 

where in your valueChanged method you update UserDefaults. Note the colon after valueChanged. This is not necessary if valueChanged has no parameter.

+1
source

All Articles