Define click event for UISegmentedControl

I have added a UISegmentedControl in my application. None of the buttons are selected in normal state. I want to implement a button click event when the first segment is selected, and another event when another button is clicked.


Solution 1:

If I understand your question correctly, you simply have to implement a target-action method (supported by UIControl which is UISegmentedControl's parent class) for the constant UIControlEventValueChanged, exactly like in the example given in UISegmentControl's reference documentation.

i.e.

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

used for a message with the following signature:

- (void)action:(id)sender

or

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

for

- (void)action:(id)sender forEvent:(UIEvent *)event

or

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

for the simplest method:

- (void)action

which are standard types of target-action selectors used in UIKit.

Solution 2:

try this:

- (IBAction)segmentSwitch:(UISegmentedControl *)sender {
      NSInteger selectedSegment = sender.selectedSegmentIndex;

      if (selectedSegment == 0) {

      }
      else{

      }
    }

Solution 3:

Simple version in swift updated

func loadControl(){
     self.yourSegmentedControl.addTarget(self, action: #selector(segmentSelected(sender:)), forControlEvents: .valueChanged)
}

func segmentSelected(sender: UISegmentedControl)
{
    let index = sender.selectedSegmentIndex

    // Do what you want
}

Solution 4:

Try this one,

    UISegmentedControl  * travelModeSegment = [[UISegmentedControl alloc] initWithItems:
    [NSArray arrayWithObjects:NSLocalizedString(@"Driving", nil),                 NSLocalizedString(@"Walking", nil), nil]];
    [travelModeSegment setFrame:CGRectMake(9.0f, 0.0f, 302.0f, 45.0f)];
    [cell addSubview:travelModeSegment];
    [travelModeSegment release];

then write an action,

     if (travelModeSegment.selectedSegmentIndex == 0) {
        //write here your action when first item selected
    } else {
        //write here your action when second item selected
    }

I hope it will help you

Solution 5:

It's worth noting that the selector has to match a method exactly, but without the actual parameters.

@selector(action)
    => -(void) action { ..code.. }

@selector(action:) 
    => -(void) action:(id)sender { ..code.. }

@selector(action:forEvent:) 
    => -(void) action:(id)sender forEvent:(UIEvent *)event { ..code.. }

This confused me for the longest time, and it's not quite clear from the earlier answers.