Search code examples
iosswiftuipangesturerecognizer

How to detect which view is being pan gestured Swift


I have a function that adds a UIImageView to the View Controller every second, and I'm trying to make each of these image views draggable with UIPanGestureRecognizer. However, I do not know how to detect which of the many image views is being dragged in my selector function. I don't want to have to use the touchesBegan(_:with:) function along with the UIPanGestureRecognizer because that could get messy. Any help would be appreciated.

Here is my code so far:

    //Function that executes every second and adds imageView
    @objc func addBalloonToDrag(){
        var myImageView=UIImageView()

        var fullWidth=Int(gameView.frame.width)
        var fullHeight=Int(gameView.frame.height)

        var widthMin=Int(gameView.frame.width*0.2)
        var widthMax=Int(gameView.frame.width*0.3)
        var randomWidth = 30
        var countdownLabelHeight=Int(countdownTimer.frame.height)

        var randomX=Int.random(in: 0...fullWidth-randomWidth)
        var randomY=Int.random(in: countdownLabelHeight...fullHeight-randomWidth)

        myImageView.frame=CGRect(x: randomX, y: randomY, width: randomWidth, height: randomWidth)

        var moodBalloonNames=["mood1","mood2","mood4","mood5"]
        var randomMoodBalloonInt=Int.random(in:0...moodBalloonNames.count)
        var randomBalloonName=moodBalloonNames[randomMoodBalloonInt]

        myImageView.image = UIImage(imageLiteralResourceName: "\(randomBalloonName)").withRenderingMode(.alwaysTemplate)

        //adding pan gesture recognizer to the image view
        var panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedView(_:)))
        myImageView.isUserInteractionEnabled = true
        myImageView.addGestureRecognizer(panGesture)

        gameView.addSubview(myImageView)
    }

    @objc func draggedView(_ sender:UIPanGestureRecognizer){
        if (stopButton.titleLabel!.text == "  Pause  ")&&((totalSec != 0)||(totalMin != 0)){
            let translation = sender.translation(in: self.view)

            //How do I know which view to drag here?
            viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
            sender.setTranslation(CGPoint.zero, in: self.view)
        }
    }

Solution

  • You can see the panGestureRecognizer.view as an imageView and then its image property.