如何检测正在平移手势的视图 Swift

How to detect which view is being pan gestured Swift

我有一个函数可以每秒向视图控制器添加一个 UIImageView,我正在尝试使每个图像视图都可以使用 UIPanGestureRecognizer 拖动。但是,我不知道如何检测在我的选择器函数中拖动了众多图像视图中的哪一个。我不想必须将 touchesBegan(_:with:) 函数与 UIPanGestureRecognizer 一起使用,因为那样会变得混乱。任何帮助将不胜感激。

到目前为止,这是我的代码:

    //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)
        }
    }

您可以看到 panGestureRecognizer.view 作为 imageView,然后是它的图像 属性。