How to detect change in UISegmentedControl from a separate IBAction

Here is a Tutorial using UISegmentedControl in iOS.

Just Create a Reference object and wire it properly to File Owner.

IBOutlet UISegmentedControl *segmentedControl;

Then set property

@property (strong, nonatomic) IBOutlet UISegmentedControl * segmentedControl;

Synthesize in .m file

@synthesize segmentedControl;

Now You can Access the selected index at any time.

- (IBAction)decodeButton:(id)sender {

    if (segmentedControl.selectedSegmentIndex == 0) {
                decode(textToDecode);
    } else if(segmentedControl.selectedSegmentIndex == 1) {
                decode1(textToDecode);
    } else if(segmentedControl.selectedSegmentIndex == 2) {
                decode2(textToDecode); 
    }
}

You should remove UISegmentedControl *segment = [UISegmentedControl alloc] ; from your code, as it allocs anew instance of your UISegmentedControl every time, instead,

create an outlet for you UISegmentController like

@property (strong, nonatomic) IBOutlet UISegmentedControl * segment;

and then later at any point in your viewcontroller.m file, you can get the currently selected segment by using

segment.selectedSegmentIndex;

Hope this make sense,

Regards


Your code alloc every time UISegmentedControl in the button press action. So use the following code for sUISegmentedControl creation and its action .

 SegmentChangeView=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"Segment1",@"Segment2",@"Segment3",nil]];
    SegmentChangeView.frame=CGRectMake(5, 44, self.view.bounds.size.width-10, 33);
    SegmentChangeView.selectedSegmentIndex=0;
    SegmentChangeView.segmentedControlStyle=UISegmentedControlStyleBar;
    SegmentChangeView.momentary = YES;
    [SegmentChangeView setTintColor:[UIColor blackColor]];
    NSDictionary *attributes =[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:13],UITextAttributeFont,nil];
    [SegmentChangeView setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [SegmentChangeView addTarget:self action:@selector(SegmentChangeViewValueChanged:) forControlEvents:UIControlEventValueChanged];
    SegmentChangeView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
    [self.view addSubview:SegmentChangeView];

-(IBAction)SegmentChangeViewValueChanged:(UISegmentedControl *)SControl
{
    if (SControl.selectedSegmentIndex==0)
    {
          decode(textToDecode);
    }
    else if (SControl.selectedSegmentIndex==1)
    {
            decode1(textToDecode);
    }
else if (SControl.selectedSegmentIndex==2)
    {
            decode2(textToDecode);
    }


}