多个UIImageView上的一个轻击手势

时间:2017-08-16 03:06:24

标签: ios swift uitapgesturerecognizer

我有2个UIImageView和一个tapGestureRecognizer。

 override func viewDidLoad() {
        // Do any additional setup after loading the view.

        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

        cameraUIImageView.isUserInteractionEnabled = true
        cameraUIImageView.addGestureRecognizer(tapGestureRecognizer)

        plus1UIImageView.isUserInteractionEnabled = true
        plus1UIImageView.addGestureRecognizer(tapGestureRecognizer)
//        


    }

我只能点击第二个UIImageView,即plus1UIImageView。

为什么?

3 个答案:

答案 0 :(得分:3)

UIGestureRecognizer必须仅与单个视图一起使用。您正在为两个视图使用相同的对象。试试这个。

override func viewDidLoad() {
    // Do any additional setup after loading the view.

    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

    cameraUIImageView.isUserInteractionEnabled = true
    cameraUIImageView.addGestureRecognizer(tapGestureRecognizer)


    let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

    plus1UIImageView.isUserInteractionEnabled = true
    plus1UIImageView.addGestureRecognizer(tapGestureRecognizer2)        
}

答案 1 :(得分:1)

您只能在一个视图中添加手势识别器,因此当您将手势识别器添加到第二个视图时,它会从第一个视图中删除。更深入的回答:

Can you attach a UIGestureRecognizer to multiple views?

答案 2 :(得分:0)

正如所有人所说,你只能在一个视图中添加一个手势识别器。虽然如果您在同一超级视图中的两个图像视图都可以向其超级视图添加点击手势并访问其子视图。您可以使用hitTest:方法检查抽头的子视图并参考抽头的imageview。检查我以前的ans here。如果您对评论有任何疑问,请与我们联系。