0

Exactly what the title implies. How do the gesture recognizers work, specifically UIGestureRecognizer. Here is a small snippet of my code

var keyboardDismiser: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer:") keyboardDismiser.direction = .Right | .Left noteView.addGestureRecognizer(keyboardDismiser)

and

    func gestureRecognizer(sender: UISwipeGestureRecognizer!) {
    println("swipe")
    self.view.endEditing()
}

My goal is to dismiss the keyboard when switching from view to view in a UIScrollView with 3 pages. What am I doing wrong? There isn't much documentation on this in Swift.

elito25
  • 624
  • 1
  • 6
  • 14

2 Answers2

2

First you setting the recognizer on the note view. It will only be active on the note view.

In addition, you are not setting direction correctly. You are setting then changing the it's value. To set it to both right and left, you use the | operator. Also direction knows it a UISwipeGestureRecognizerDirection so you don't need specify that.

var keyboardDismiser = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer:")
keyboardDismiser.direction = .Right | .Left
self.view.addGestureRecognizer(keyboardDismiser)

Finally, I would use endEditing() instead of resignFirstResponder().

func gestureRecognizer(sender: UISwipeGestureRecognizer!) {
    println("swipe")
    self.view.endEditing(true)
}

Hope that helps.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • The code is still not working. It seems like the function is not being called. – elito25 Jun 15 '14 at 01:02
  • @elito25 update the question: in what method do you have `keyboardDismiser`? – Jeffery Thomas Jun 15 '14 at 01:05
  • The keyboardDismiser is in the ViewController method under viewDidLoad while the gestureRecognizer function is within ViewController but not under ViewDidLoad – elito25 Jun 15 '14 at 01:19
  • @elito25 sorry, I don't know if I can be of much more help. You will need to attach a debugger and look at the view hierarchy, see if there is something which interferes with the gesture. – Jeffery Thomas Jun 15 '14 at 01:31
  • Thank you anyway. I am looking up the combination of UIScrollView and UIGestureRecognizers and it seems like they don't play well together. – elito25 Jun 15 '14 at 01:35
  • I am looking at it using a debugger to find the hierarchy, and it isn't even showing up.There is no Gesture recognizer in the hierarchy. – elito25 Jun 15 '14 at 01:47
1

I believe that selectors in Swift do not need the : at the end; they're just a string with the name of the function: gestureRecognizer. So this is what you should have:

var keyboardDismiser = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer")

Relevant question here.

Community
  • 1
  • 1
Alex
  • 5,009
  • 3
  • 39
  • 73