Nadal Alyafaie Nadal Alyafaie - 4 years ago 327
Swift Question

Swift : Set UIPanGestureRecognizer to UIView

Im trying to set up a UIPanGestureRecognizer to a specific UIView

self.halfViewBlue.frame = CGRectMake(0, 0, self.bounds.width / 2, self.bounds.height)
self.halfViewBlue.backgroundColor = UIColor.blueColor()
halfViewBlue.alpha = 1.0
self.addSubview(self.halfViewBlue)

self.halfViewRed.frame = CGRectMake(self.frame.midX, 0, self.bounds.width / 2, self.bounds.height)
self.halfViewRed.backgroundColor = UIColor.redColor()
halfViewRed.alpha = 1.0
self.addSubview(self.halfViewRed)

//Pan Gesture for Red
let panGestureRed = UIPanGestureRecognizer()
panGestureRed.addTarget(self, action: "handlePanRed:")
self.addGestureRecognizer(panGestureRed)
self.userInteractionEnabled = true

//Pan Gesture for Blue
let panGestureBlue = UIPanGestureRecognizer()
panGestureBlue.addTarget(self, action: "handlePanBlue:")
self.addGestureRecognizer(panGestureBlue)
self.userInteractionEnabled = true

}

func handlePanRed(gesture : UIPanGestureRecognizer){

if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){

let velocity : CGPoint = gesture.velocityInView(halfViewRed)

//Pan Down
if(velocity.y > 0){
print("Panning down")
hideRedBar()
produceBlueBar()
}
//Pan Up
if(velocity.y < 0){
print("panning up")
hideBlueBar()
produceRedBar()
}
}
}


func handlePanBlue(gesture : UIPanGestureRecognizer){

if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){

let velocity : CGPoint = gesture.velocityInView(halfViewBlue)

//Pan Down
if(velocity.y > 0){
print("Panning down")
hideBlueBar()
produceRedBar()
}

if(velocity.y < 0){
print("panning up")
hideRedBar()
produceBlueBar()

}
}
}


Here I simply create two UIViews, both split vertically across the screen(equally).
I then add two panGestures and a function to follow it. My issue is that the only panGesture that gets recognized is the "panGestureBlue" and weirdly i can control it on any part of the screen, not just the half where the "halfViewBlue" is.
So I'm assuming that both panGestures are being added to self.view and not the UIView it is suppose to be put with, and the "panGestureBlue" is being read in because it is added after "panGestureRed". Instead of "self" in the "panGestureBlue.addTarget" i tried putting "halfViewBlue", but it crashed.

How can i fix this issue!?

Answer Source

You should add the pan gesture on the subviews not the superview, like this:

self.halfViewRed.addGestureRecognizer(panGestureRed)
self.halfViewBlue.addGestureRecognizer(panGestureBlue)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download