0

I am creating a UIButton in Swift with the following code:

let button = UIButton()
button.addTarget(self, action: "tileSwiped:", forControlEvents: .TouchDragExit)

My tileSwiped function definition is as follows:

func tileSwiped(button: UIButton) {
}

What I would like to do is determine which direction the TouchDragExit event occurred in. More specifically, my button is a rectangle, and I would like to know if the drag exited on the top, bottom, left, or right edge of the rectangle.

However, I don't see a way to do this without having access to the motion event that triggered the function call. But of course, I can't change the parameters passed to the tileSwiped function. So how can I get the direction of the "swipe"?

(I'm open to changing my approach to listening for the gesture because I don't think this approach will get me anywhere, but note that I do need to keep the button as a parameter.)

kmell96
  • 1,365
  • 1
  • 15
  • 39

1 Answers1

3

It would be easier to use a UISwipeGestureRecognizer, see Apple Documentation.

What you want to do is:

  1. Create a UISwipeGestureRecognizer
  2. Specify which direction you want to recognize
  3. Add this recognizer to the button
  4. Implement the callback method

Example:

let button = UIButton();
// 1
let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipe:");
// 2
swipeGestureRecognizer.direction = .Left
// 3
button.addGestureRecognizer(swipeGestureRecognizer)

.

// 4
func swipe(gestureRecognizer: UISwipeGestureRecognizer) {
    NSLog("left")
}
averello
  • 114
  • 1
  • 5
  • This doesn't really work in my case because I have an array of UIButtons and the action I perform has to change based on which button is swiped. In other words, I would need the UIButton to be passed to the swipe function as a parameter as well. – kmell96 Jan 26 '16 at 07:59
  • 1
    Was able to build on your answer to get one that works for me. The UISwipeGestureRecognizer has a property called "view" that gives you the button associated with it. You have to do: (gestureRecognizer.view as? UIButton)! – kmell96 Jan 26 '16 at 08:41