UISegmentedControl fires ValueChanged when loading selectedindex
I have a UISplitViewController
utility type app where each UIViewController
handles various calculations. I have a popover with segmented controls that allows the user to set certain options. The problem I have is when saving and reloading the contents of UITextfields
and the selected segment index, if the segment control index was saved and is == 1 a valuechanged event is fired off from viewdidload
as the state is set from
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
theDepthSegment.selectedSegmentIndex = [[defaults objectForKey:@"updateMe"] intValue];
Is there anyway to prevent valuechanged being fired as the selectedsegment is set in view did load? or maybe someway to determine the difference between touch events versu开发者_开发技巧s code
It seems strange this happens, maybe there is another way....
Thank You
Considering the view is just loading, the segmented control doesn't have a previous value, so it will assume it is indeed being changed and acts accordingly. One way you could potentially get around this is to set up a BOOL
value in your IBAction
method linked to the segmented control. At the beginning of your viewDidLoad
method, say wasLoaded = NO
(where wasLoaded
will need to be declared in your header file). Then you'll assign your selectedSegmentIndex
. Afterwards, declare wasLoaded = YES
. Finally, in your IBAction
method, say something like
if (wasLoaded) {
// do what you need to do since this isn't when it's being initialized
}
The quickest way to get this done is to detach the IBAction
in the interface builder and add a addTarget:action:forControlEvents:
method after you change the value in viewDidLoad
. There is no way of making a distinction between touch triggered change and a programmatic change for UIControlEventValueChanged
. You can look at touch control events but it is not the same as the value changed one.
Deepak is right. If you're not using Interface Builder to setup your UISegmentedControl
, you should first set the selected index of the UISegmentedControl
and then call addTarget:action:forControlEvents:
. Like this:
NSArray *items = [[NSArray alloc] initWithObjects:@"A", @"B", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
[items release];
[segmentedControl setFrame:CGRectMake(10, 10, 300, 46.0f)];
[segmentedControl setTag:60];
[segmentedControl setSelectedSegmentIndex:savedSelectedIndex];
[segmentedControl addTarget:self action:@selector(segControlClicked:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentedControl];
[segmentedControl release];
精彩评论