Swift 3 - Image view with Tap Gesture

十年热恋 提交于 2019-12-03 09:23:22
Maulik Pandya

Following code may help you more with Swift 4.

As you said you want to detect image tap on tableview cell please go through this code:

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.cellTappedMethod(_:)))

cell.yourImageView.isUserInteractionEnabled = true
cell.yourImageView.tag = indexPath.row
cell.yourImageView.addGestureRecognizer(tapGestureRecognizer)

And add below method to your ViewController:

@objc func cellTappedMethod(_ sender:AnyObject){
     print("you tap image number: \(sender.view.tag)")
}

Please check isUserInteractionEnabled of UIImageView is true

I recently had an issue that seems similar to yours. I had a number of images, all of which I wanted to respond in the same way whenever the user tapped them. After some experimenting, it became clear to me that each image had to have its own UITapGestureRecognizer instance. I ended up using code like this, which ensured that every image responded to being tapped:

for imageView in imageViews {
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapResponse))
    imageView.addGestureRecognizer(tapGestureRecognizer)
    imageView.isUserInteractionEnabled = true
}

The idea is that you should create unique gesture recognizer for every UIImageView.

let gestureRecognizerOne = UITapGestureRecognizer(target: self, action: #selector(tap))
firstImageView.addGestureRecognizer(gestureRecognizerOne)

let gestureRecognizerTwo = UITapGestureRecognizer(target: self, action: #selector(tap))
secondImageView.addGestureRecognizer(gestureRecognizerTwo)

But I didn't see your code, so, maybe you should create it in a loop or something like that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!