8

I'm trying to add gesture(swipe) functionality to an existing button in my view but I can't figure out how to attach the swipe to the button's area.

The desired effect is to have a button I can press as well as swipe to produce different outcomes. So far the way I'm implementing gestures applies it to my entire view not just the button.

I have a feeling it's pretty simple but it's been escaping me for a couple of days - I might just be searching for the wrong thing.

(I'm assigning '@IBOutlet var swipeButton: UIButton!' to my button BTW)

Code below:

class ViewController: UIInputViewController {

@IBOutlet var swipeButton: UIButton!

let swipeRec = UISwipeGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loadInterface()

    var swipeButtonDown: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "ButtonDown")
    swipeButtonDown.direction = UISwipeGestureRecognizerDirection.Down
    self.view.addGestureRecognizer(swipeButtonDown)
}

@IBAction func buttonPressed(sender: UIButton) {
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText("button")
}
func buttonDown(){
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText("swipe")
}

}
glasstongue
  • 103
  • 1
  • 1
  • 8

1 Answers1

9

If you want to add swipeGesture into Button then do it like this way:

self.yourButton.addGestureRecognizer(swipeButtonDown)

and also there is a mistake in selector you sent it should be like:

var swipeButtonDown: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "buttonDown")

change ButtonDown to buttonDown

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • I set it on line 13 as follows - it keeps crashing so I'm definitely doing something wrong :D self.swipeButton.addGestureRecognizer(swipeButtonDown) – glasstongue Jan 21 '15 at 05:26
  • I edited the wrong one [here: var swipeButtonDown: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "ButtonDown")] first and didn't undo - works like a charm!!! I'd upvote you but I'm a lowly noob - Cheers! – glasstongue Jan 21 '15 at 05:41
  • Quick question - to do multiple directions do I need to assign multiple @IBOutlet var swipeButton: UIButton! – glasstongue Jan 21 '15 at 05:50
  • check this:http://stackoverflow.com/questions/24215117/how-to-recognize-swipe-in-all-4-directions – Dharmesh Kheni Jan 21 '15 at 05:52