TimeParadox
TimeParadox

Reputation: 318

swift: when I open the view controller and press the gesture recognizer for the first time it says that i pressed it twice. how to fix this?

When I open my view controller I have 4 gesture recognizers, when I tap twice this shout happen:

@IBOutlet var doubleTap: UITapGestureRecognizer!
@IBAction func doubleTapAction(sender: AnyObject) {
    doubleTap.numberOfTapsRequired = 2
    print("Button was 2x")
}

but when I press one of the 4 buttons for the first time(I pressed only one time.) it prints that I tapped twice. after the first time it works fine.

Can someone tell my how to fix this?

thanks for reading my question I hope someone can help me.

if you don't understand my question please comment.

Upvotes: 0

Views: 182

Answers (1)

Alonso Urbano
Alonso Urbano

Reputation: 2265

This is because the first time the gesture recognizer is set to recognize one single tap. You change that to be two taps, but you set it in the wrong place, because you already tapped once, so it enters the action and executed the code there:

self.doubleTap.numberOfTapsRequired = 2 // This is wrong here!
print("Button was 2x")

So it changes the recognizer to recognize two taps, but it already recognized one (that's why that code gets executed) so it prints that text as well.

It makes no sense that you set that every time you tap, you just need to do it once. A good place to do this is viewDidLoad.

You could also set the number of the required taps in the interface builder.

code example:

@IBOutlet var doubleTap: UITapGestureRecognizer!
@IBAction func doubleTapAction(sender: AnyObject) {
    print("doubleTap was 2x")
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.doubleTap.numberOfTapsRequired = 2
}

Upvotes: 1

Related Questions