Tom Mohr Tom Mohr - 3 years ago 185
iOS Question

turn off a pangesturderecognizer with a double tapgesturerecognizer and a swift flow

I have a button on my main UI that I can create views programmatically with. That is down at the bottom. They come out as a green circle that I can move around using a PanGestureRecognizer.

My goal is to turn off the PanGestureRecognizer with a TapGestureRecognizer (I would like it to be a double tap) essentially locking that specific view in place once I double tap it.

This is the code that I have so far. When I tap the view it does in fact change color, but I cannot figure out how to reference the PanGestureRecognizer to disable it.

class MakeACircle: UIView {
var circleCenter = CGPoint()
let tap = UITapGestureRecognizer()
let panGesture = UIPanGestureRecognizer()
var checkSomething = 1

init() {

super.init(frame: CGRect(x: 0.0, y: 0.0, width: 100, height: 100))
self.layer.cornerRadius = 50.0
self.backgroundColor =
self.isUserInteractionEnabled = true
UITapGestureRecognizer().numberOfTapsRequired = 2

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

func dragCircle(gesture: UIPanGestureRecognizer) {
let target = gesture.view!

switch gesture.state {
case .began, .ended:
circleCenter =
case .changed:
let translation = gesture.translation(in: self.superview) = CGPoint(x: circleCenter.x + translation.x, y: circleCenter.y + translation.y)
default: break

func freeze(gesture: UITapGestureRecognizer) {

switch checkSomething {
case 1:
self.panGesture.isEnabled = false
self.backgroundColor =
checkSomething += 1

case 2:
self.panGesture.isEnabled = true
self.backgroundColor =
checkSomething -= 1



I am creating the view programmatically with this IBButton

@IBAction func makeACircle(_ sender: UIButton) {
let something = MakeACircle()

something.addGestureRecognizer(UIPanGestureRecognizer(target: something, action: #selector(something.dragCircle(gesture:))))
something.addGestureRecognizer(UITapGestureRecognizer(target: something, action: #selector(something.freeze(gesture:)))) =


The taps work, as you can see I have a switch in there to turn it colors.. it prints the number and turns color.. but it happens with just one tap and the pan stays on.

Any insight is greatly appreciated! This is my first execution of this, I know I'm right at the door, but I just can't figure it out.

Answer Source

It looks like you're not storing a reference to self.panGesture on your MakeACircle() object when you add it, so when you try to disable it, it doesn't do anything. Where is self.panGesture being set?

instead of this:

something.addGestureRecognizer(UIPanGestureRecognizer(target: something, action: #selector(something.dragCircle(gesture:))))

try this:

something.panGesture = UIPanGestureRecognizer(target: something, action: #selector(something.dragCircle(gesture:)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download