How to handle events with multiple control segments in one view

There are two segmental controls in my viewcontroller. How can I handle the tap events of both segmented controllers?

+4
source share
6 answers

Set the tag property for each segmental control for another integer. Then, in your method, which you set as an action, when the value changes, check the integer value of the tag property using [sender tag] .

+2
source

There are two ways to do this.

  • Add different actions for each segment management
  • Add the same actions for each segment control and check which control is used with its tag.

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


     - (IBAction)segmentSwitch:(id)sender { UISegmentedControl *segmentedControl = (UISegmentedControl *) sender; if(segmentedControl.tag == someTag) { if(segmentedControl.selectedSegmentIndex == 1) { // your code } else if(segmentedControl.selectedSegmentIndex == 2) { // your code } } else if(segmentedControl.tag == someTag) { if(segmentedControl.selectedSegmentIndex == 1) { // your code } else if(segmentedControl.selectedSegmentIndex == 2) { // your code } } } 
+11
source

Apple docs says:

http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UISegmentedControl_Class/Reference/UISegmentedControl.html

You register target action methods for the segmented control using the UIControlEventValueChanged constant, as shown below.

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

So, you just need to register an action for each segmented control.

+3
source

You can use the selected segment mode:

 UISegmentedControl *tempSegment = sender; if ([tempSegment selectedSegmentIndex] == 0){ //first Action } else if ([tempSegment selectedSegmentIndex] == 1){ //second Action } 
+2
source

Assign two different actions to these segmented controls:

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

Quick version:

  @IBAction func yourFunctionName(sender: UISegmentedControl) { if (sender.selectedSegmentIndex == 0){//choice 1 }else{//choice 2 } } 
-1
source

Source: https://habr.com/ru/post/1382998/


All Articles