0
let aButton = UIButton()
a.addTarget(self, action: "handler:", forControlEvents: .TouchUpInside)

func handler(btn: UIButton) {
    //Is there anyway can I know the controlEvent is "TouchUpInside" in this method?
}

as the example above, I wanna know the ControlEventType at @selector, could not found the correct API or it's impossible?

pangyulei
  • 39
  • 7

3 Answers3

2

You can either provide different methods for the different control events:

a.addTarget(self, action: "touchDownHandler:", forControlEvents: .TouchDown)
a.addTarget(self, action: "touchUpHandler:", forControlEvents: .TouchUpInside)

func touchDownHandler(btn: UIButton) {
}

func touchUpHandler(btn: UIButton) {
}

As noted in another answer you can also get the event in your handler and inspect that for the type of touch, here it is in Swift:

a.addTarget(self, action: "handleTouch:event:", forControlEvents: .AllTouchEvents)

// ...

func handleTouch(button: UIButton, event: UIEvent) {
    if let touch = event.touchesForView(button)?.first as? UITouch {
        switch touch.phase {
        case .Began:
            println("touch began")

        case .Ended:
            println("touch ended")

        case .Moved:
            println("touch moved")

        case .Cancelled:
            println("touch cancelled")

        case .Stationary:
            println("touch stationary")

        }
    }
}
Community
  • 1
  • 1
Steve Wilford
  • 8,894
  • 5
  • 42
  • 66
2

You can change your action to take the event parameter, like this:

[button addTarget:self action:@selector(callback:event:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchCancel];

-(void)callback:(UIButton *)button (UIEvent*)event {
    ...
}

Adding a second parameter to your callback will make Cocoa pass the event to you, so that you could check what has triggered the callback.

thanks to dasblinkenlight

Community
  • 1
  • 1
Saurabh Prajapati
  • 2,348
  • 1
  • 24
  • 42
0

I'm afraid you have to create multiple functions (which could then call a common handler function, of course):

a.addTarget(self, action: "handleTouchUpInside:", forControlEvents: .TouchUpInside)
a.addTarget(self, action: "handleTouchUpOutside:", forControlEvents: .TouchUpOutside)

You are allowed to add an action which accepts an extra UIEvent parameter, but unfortunately it won't contain any information about the control event type.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109