问题
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?
回答1:
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)")
}
回答2:
Please check isUserInteractionEnabled
of UIImageView
is true
回答3:
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
}
回答4:
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.
来源:https://stackoverflow.com/questions/42161476/swift-3-image-view-with-tap-gesture