Maysam Maysam - 5 days ago 5
Swift Question

UIPanGestureRecognizer does not work

It's weird, but when I add a

UIPanGestureRecognizer
to a view it does not work. It's my view, that white view is a subview of the red view:

enter image description here

Main View:

@IBOutlet weak var redView: UIView!
@IBOutlet weak var whiteView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
whiteView.gestureRecognizers = [panRecognizer]
}


func handlePan(recognizer:UIPanGestureRecognizer) {
//foo
}


When I tap and drag the white view it won't move.

Answer

Here is the answer:

class ViewController: UIViewController {

    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var whiteView: UIView!

    var lastLocation:CGPoint = CGPointMake(0, 0)


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
        whiteView.addGestureRecognizer(panRecognizer)

    }


    func handlePan(recognizer:UIPanGestureRecognizer)  {
        let translation  = recognizer.translationInView(redView)
        whiteView.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // Promote the touched view
        lastLocation = whiteView.center

    }
}
Comments