Alex Bollbach
Alex Bollbach

Reputation: 4600

Detect what type of event triggered a UIControl's action

I have a custom UIControl subclass with an action method callback. I want to display the value of the control element on a UILabel while it is being adjusted, and then I want the label to become hidden when the user stops adjusting the control.

Therefore, I have connected the action for both UIControlEventValueChanged and UIControlEventTouchUpInside. Both successfully invoke my action method. However, to do different things in this method based on the action I need to know which event triggered the method. How can I do this? I've looked through UIControl and don't see an obvious property. state seems to return 1 for both actions.

So something like this:

    - (void)handleSlider1:(CustomSlider*)sender {

        if (sender.state == UIControlEventValueChanged) {
            // code
        } else {
            // different code
        }
    }

Upvotes: 2

Views: 492

Answers (2)

jscs
jscs

Reputation: 64022

You can distinguish the two events pretty easily by connecting them each to separate IBActions. Each new action then would call your single handler, passing the appropriate UIControlEvent value along:

- (IBAction)sliderValueChanged:(CustomSlider *)slider
{
    [self handleSlider1:slider forEvent:UIControlEventValueChanged];   
}

- (IBAction)sliderValueChanged:(CustomSlider *)slider
{
    [self handleSlider1:slider forEvent:UIControlEventTouchUpInside];   
}

- (void)handleSlider1:(CustomSlider *)sender forEvent:(UIControlEvents)event
{
    if (event == UIControlEventValueChanged)
    //...
}

Upvotes: 1

oroboto
oroboto

Reputation: 226

If you want to use the same method to handle both events then you can check the highlighted property of the control:

if (sender.highlighted) {
   // slider is changing value (value changed)
} else {
   // slider has stopped changing value (touch up inside)
}

Alternatively, you could simply create two separate action methods and connect each event to the required method.

Upvotes: 0

Related Questions