Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 805
Warrior Avatar asked Jun 15 '10 21:06

Warrior


People also ask

What is segmented control used for?

A segmented control is a horizontal set of two or more segments. It's used as toggles for features or content, similar to radio buttons but more visible and promote exploration.

How do I create a custom segment in Swift?

Click on the UIView , go to the identity inspector, and give the custom class the name BetterSegmentedControl for your UIView . Xcode will build your project so wait until the build finishes, then you have a custom segment on your UIView .

How do you implement segment control in Swift?

Enter Swift as Language and choose Next. Go to the Storyboard and drag a Segmented Control to the top of the main view. Also drag a Label to the view and place it below the Segmented Control. Select the label and give it a text of First Segment selected.


3 Answers

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.

like image 87
macbirdie Avatar answered Nov 01 '22 03:11

macbirdie


try this:

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

      if (selectedSegment == 0) {

      }
      else{

      }
    }
like image 44
Nuno Ferro Avatar answered Nov 01 '22 03:11

Nuno Ferro


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
}
like image 45
Beninho85 Avatar answered Nov 01 '22 03:11

Beninho85