简体   繁体   中英

UITapGestureRecognizer on custom table view cell doesn't work

I'm trying to add a gesture recognizer for an image in a custom table view cell. For some reason I can't seem to make it work though. Here's my code

override func awakeFromNib() {
    super.awakeFromNib()

    heartImage.userInteractionEnabled = true
    let gesture = UITapGestureRecognizer(target: self, action:Selector("onHeartTap"))
    gesture.delegate = self
    heartImage.addGestureRecognizer(gesture)
}

func onHeartTap(sender: UITapGestureRecognizer) 
    print("TAPPED")
}

The function awakeFromNib() gets called correctly, but onHeartTap() never gets called when tapping the image. What am I doing wrong?

User interaction was enabled for the image but not for the cell.

Enabled it for the cell from the storyboard and everything works. Thanks for the help everybody!

In your selector name 'onHeartTap' ":" is missing

just replace

let gesture = UITapGestureRecognizer(target: self, action:Selector("onHeartTap")) 

with

let gesture = UITapGestureRecognizer(target: self, action:Selector("onHeartTap:"))

And also any specific reason you are doing this in awakeFromNib?? You can do this on viewWillAppear also.

I had a similar problem, that a UIImageView in a UITableViewCell subclass would not trigger the gesture recognizer that I set up.

func viewDidLoad() {
    imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(imageViewTapped(sender:))))
    imageView.isUserInteractionEnabled = true
}

the problem was the viewDidLoad() is not called for UITableViewCell:
Can I use viewDidLoad method in UITableviewCell?

set the gesture recognizer in awakeFromNib() instead:

override func awakeFromNib() {
    imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(imageViewTapped(sender:))))
    imageView.isUserInteractionEnabled = true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM