1

In other words: I have one button with two events, how to capture UIControlEventTouchDown and UIControlEventTouchUpInside in the callback function setRedPos?

[btnRedPos addTarget:self action:@selector(setRedPos:) forControlEvents:UIControlEventTouchDown];// I want to pass in a value of 0
[btnRedPos addTarget:self action:@selector(setRedPos:) forControlEvents:UIControlEventTouchUpInside];// I want to pass in a value of 1

...

- (void) setRedPos:(UIButton*)btn
{

}
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 1
    possible duplicate of [Passing parameters to addTarget:action:forControlEvents](http://stackoverflow.com/questions/3988485/passing-parameters-to-addtargetactionforcontrolevents) – cHao Jun 20 '12 at 23:33

3 Answers3

4

You can't pass arbitrary parameters via target/action. The first parameter is sender, and the second (if you set it up this way) is the event. You could use the event to tell what kind of event triggered it, like so:

[btnRedPos addTarget:self action:@selector(setRedPos:forEvent:) 
    forControlEvents:UIControlEventTouchDown];
[btnRedPos addTarget:self action:@selector(setRedPos:forEvent:) 
    forControlEvents:UIControlEventTouchUpInside];


- (void) setRedPos:(id)sender forEvent:(UIEvent*)event
{
    UITouch* aTouch = [[event allTouches] anyObject];
    if( aTouch.phase == UITouchPhaseBegan ) {
        NSLog( @"touch began" );
    }
    else if( aTouch.phase == UITouchPhaseEnded ) {
        NSLog( @"touch ended" );
    }
}
zpasternack
  • 17,838
  • 2
  • 63
  • 81
1

Use two separate selectors.

- (void)setRedPosDown:(UIButton *)button {
    [self setRedPos:button state:0];
}
- (void)setRedPosUp:(UIButton *)button {
    [self setRedPos:button state:1];
}

[btnRedPos addTarget:self action:@selector(setRedPosDown:) forControlEvents:UIControlEventTouchDown];
[btnRedPos addTarget:self action:@selector(setRedPosUp:) forControlEvents:UIControlEventTouchUpInside];
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
0

The only two ways I know to achieve that in one method are: 1) the method zpasternack describes 2) Using two separate buttons one for the touch up one for the touch down and test the sender.

The first method is better in your case since it is with only one button object. The second would be useful if you were looking for one method achieving the actions of different buttons.

Try to stick the closer to the physical representation. One button but two different actions? The the code has only one button and tests the actions.

fBourgeois
  • 316
  • 2
  • 10