Search code examples
objective-cuibuttonuisegmentedcontrolibaction

Segmented Control not affecting if loop in -(IBaction) method


I am making an IOS app which plays wav files on the press of a UIButton. I am attempting to implement a UISegmentedcontrol, in order to change which sample is being played when a different segment is highlighted.

Here is my code for my viewController.h:

@property (nonatomic, retain) IBOutlet UISegmentedControl *segmentedControl;
-(IBAction)playFile1;
-(IBAction)playFile2;
-(IBAction)playFile3;
@end

and viewController.m

@synthesize segmentedControl = segmentedControl;
-(IBAction)playFile1{
    if([segmentedControl selectedSegmentIndex] == 0){
    [rtcmixmanager playFile1];
    }
    else if([segmentedControl selectedSegmentIndex] == 1){
    [rtcmixManager playFile2];
    }
    else{
    [rtcmixManager playFile3];
    }
}

I have tried both this method, and adding a similar if statement in the RTCMixManager.m file under the -(IBaction) method itself, with no luck. The project will compile but it seems to only play file 1, no matter which segment is highlited. does anyone know why this is?


Solution

  • Try this:

    -(IBAction)segmentChanged:(id)sender{
        UISegmentedControl *segControl = ((UISegmentedControl *)sender);
        if([segControl selectedSegmentIndex] == 0){
            [rtcmixmanager playFile1];
        }else if([segControl selectedSegmentIndex] == 1){
            [rtcmixManager playFile2];
        }else{
            [rtcmixManager playFile3];
        }
    }
    

    And connect it to the "value changed" of the Segmented Control event in the .xib file

    Edit: You can also do it in code like this:

    [segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];