mstace mstace - 4 months ago 26
Objective-C Question

How to Detect Change in UISegmentedControl from a Separate IBAction

I have a

UISegmentedControl
button with three segments.
In
ViewController.m
this is working just fine -- pressing the buttons fires the correct methods.

I have another separate
UIButton
that when it is pressed it needs to first CHECK the state of the
UISegmentedControl
(to see which button is currently pressed) and then fire a method according to that segment value.

Here is my code for that separate
UIButton
. The button itself is working, but I cannot seem to figure out how to GET the current value of the segment of the
UISegmentedControl
.

Many thanks for any assistance here.
I am new to
OBJ-C
. I know how to do this in
VisualBasic
, so answers that are on the more verbose side would be most appreciated as I need to know the 'why'. Thank you.

- (IBAction)decodeButton:(id)sender {
UISegmentedControl *segment = [UISegmentedControl alloc]; // THIS DOES NOT WORK.

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

Answer

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); 
    }
}
Comments