Swift:如何使用 touchesBegan/Moved 管理多个可拖动的 uiimageview

Swift: how to manage multiple draggable uiimageviews with touchesBegan/Moved

我刚刚创建了两个 moving/draggable UIImageView,它们应该在下面更大的 UIImageView 上移动,如下面的屏幕截图:

这是我的代码:

class PhotoViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var redA: UIImageView!
@IBOutlet weak var redB: UIImageView!

var imagePicker: UIImagePickerController!
var redLocationA:CGPoint = CGPoint(x:0, y:0)
var redLocationB:CGPoint = CGPoint(x:0, y:0)

override func viewDidLoad() {
    super.viewDidLoad()
    self.redA.center = CGPointMake(80, 330)
    self.redB.center = CGPointMake(80, 360)
    // Do any additional setup after loading the view, typically from a nib.
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.redLocationA = (touches.first?.locationInView(self.view))!
    self.redA.center = redLocationA

    self.redLocationB = (touches.first?.locationInView(self.view))!
    self.redB.center = redLocationB
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.redLocationA = (touches.first?.locationInView(self.view))!

    if ((redLocationA.x >= 26 && redLocationA.x <= 292) && (redLocationA.y >= 71 && redLocationA.y <= 461)){
        redA.center = redLocationA
    }

    if ((redLocationB.x >= 26 && redLocationB.x <= 292) && (redLocationB.y >= 71 && redLocationB.y <= 461)){
        redB.center = redLocationB
    }

    print("redA: \(redLocationA)")
    print("redB: \(redLocationB)")
}

...
}

正如您想象的那样,当我点击一个图钉时,另一个图钉也会移动到第一个图钉的位置,我认为这是因为我总是从 touches: Set<UITouch> 执行相同的提取。 管理两个引脚的正确方法是什么,而不会在每次敲击时将第一个引脚的位置覆盖在第二个引脚的位置上? 谢谢

如果你想按下并拖动一个 imageView,你应该为每个 imageView 添加一个 panGestureRecognizer