使用Swift中的UITapGestureRecognizer检查哪个图像视图被按下了

时间:2017-01-24 21:30:51

标签: swift uitapgesturerecognizer

我有三个UITapGestureRecognizers 它们看起来像那样:

gestureImageViewUp = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewUp.addGestureRecognizer(gestureImageViewUp)

gestureImageViewDown = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewDown.addGestureRecognizer(gestureImageViewDown)

gestureImageViewMiddle = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewMiddle.addGestureRecognizer(gestureImageViewMiddle)

我想检查哪一个被按下了。我该如何解决?

1 个答案:

答案 0 :(得分:2)

您不需要多个识别器,只需将其附加到视图中,然后在选择器中检查单击了哪个图像视图。

func onPress(_ guesture: UIGestureRecognizer) {

    guard let location = guesture.location(in: self.view)  else { return }

    if gestureImageViewUp.frame.contains(location) {
        // …
    }
    if gestureImageViewDown.frame.contains(location) {
        // …
    }
    if gestureImageViewMiddle.frame.contains(location) {
        // …
    }
}

未经测试抱歉,如果您粘贴代码而不是快照会更容易