我有一个函数,它每秒向视图控制器中添加一个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,然后查看其image属性。

关于ios - 如何检测哪个 View 正在平移手势,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57751667/

10-10 21:12