Search code examples
iosswiftswift3gesture

Swift 3 - Image view with Tap Gesture


Im having issues with using a tap gesture that I have put on an image view. The image is currently stored in the Assets as 'ActionLiked' and I have set the image view to this image. It is then rendered into a table view which is dynamic based on JSON (so it repeats for each item I put into a JSON array). I added the tap gesture to print out 'TAPPED' each time I click on it however, it seems to not be working all the time - 7 items currently in the table, the tap gesture will work on 1 then not work on the next 2 then work on the 4th one and repeat that pattern

ITEM 1 - WORK ITEM 2 - NO WORK ITEM 3 - NO WORK ITEM 4 - WORK ITEM 5 - NO WORK ITEM 6 - NO WORK ITEM 7 - WORK

I get an error in my debug console Could not load the "" image referenced from a nib in the bundle with identifier But the image is showing correctly on each one just not recognising the tap gesture?


Solution

  • 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)")
    }