Search code examples
objective-cioscocoa-touchuisegmentedcontrol

UISegmentedControl calls action method on changing selectedSegmentIndex programmatically


I have a a UISegmentedControl in my xib file. It is linked to an action method on value changed event in the xib file.

When I programmatically set the value of selectedSegmentIndex the action method gets called

mysegmentedcontrol.selectedSegmentIndex = index

I was expecting that the action method would only be called when the user changes the control by touching it?

This happens only for UISegmentedControl.


Solution

  • .h file

    BOOL isProgramaticallyChanged;
    

    .m file

    - (IBAction)segmentAction:(id)sender { // valuechanged connected function
    
            UISegmentedControl *segControll = (UISegmentedControl *)sender;
    
        if (segControll.tag == 55) { // while create segment specify tag value to 55 (to set use via IB or Code)
    
            if (isProgramaticallyChanged == NO) {
    
                // your valuechanged code here
    
            }
    
            else {
    
                isProgramaticallyChanged = NO; //important
    
            }
    
        }
    
        else if (segControll.tag == 66) { // for many segments
    
        }
    
            //...like this do for all segments
    }
    

    in .m file

    wherever you put this code to change programmatically do before that like this

    if (mysegmentedcontrol.selectedSegmentIndex != index) {
    
        isProgramaticallyChanged = YES;
    
        mysegmentedcontrol.selectedSegmentIndex = index;
    
    }