kmell96
kmell96

Reputation: 1465

Swift Get Direction of Swipe Gesture

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.)

Upvotes: 0

Views: 1225

Answers (1)

averello
averello

Reputation: 114

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")
}

Upvotes: 3

Related Questions