-1

I am relatively new to swift programmming, I found that when the gesture recognizers are global variables they dont work like below.

    var monkeyViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    var bananaViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))


 override func viewDidLoad() {
        super.viewDidLoad()
        MonkeyView.addGestureRecognizer(monkeyViewPanGesture)
        BananaView.addGestureRecognizer(bananaViewPanGesture)
        view.backgroundColor = .white
        view.addSubview(MonkeyView)
        view.addSubview(BananaView)
        setContriants()
    }

But when I move them into the viewDidLoad function they work

override func viewDidLoad() {
    super.viewDidLoad()
    let monkeyViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    let bananaViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    MonkeyView.addGestureRecognizer(monkeyViewPanGesture)
    BananaView.addGestureRecognizer(bananaViewPanGesture)
    view.backgroundColor = .white
    view.addSubview(MonkeyView)
    view.addSubview(BananaView)
    setContriants()
}

Can anyone explain why is happens

Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24

2 Answers2

1

gestures dont work like that. you need to create a generic function that will handle gestures.

func addGestureTo(view : UIView) {
   let monkeyViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
   view.addGestureRecognizer(monkeyViewPanGesture)
}

Call this function from anyplace from where it's accessible

override func viewDidLoad() {
    super.viewDidLoad() 
    addGestureTo(view : yourDesiredView) 
}
Abdul Waheed
  • 863
  • 8
  • 14
  • why dont they work like that – Tiisetso Tjabane Sep 14 '19 at 11:36
  • Gesture Recognizers Are Attached to a View Every gesture recognizer is associated with one view. By contrast, a view can have multiple gesture recognizers, because a single view might respond to many different gestures. For a gesture recognizer to recognize touches that occur in a particular view, you must attach the gesture recognizer to that view. .. Reference here https://stackoverflow.com/a/31274865/5259363 – Abdul Waheed Sep 16 '19 at 05:10
1

If you need to keep a reference to the gesture you could do something like this:

weak var panGesture: UIPanGestureRecognizer?

override func viewDidLoad() {
    super.viewDidLoad()
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
    self.view.addGestureRecognizer(panGesture)
    self.panGesture = panGesture
}

@objc func handlePan(_ sender: UIPanGestureRecognizer) {
    // do your thing with the gesture        
}