UITapGestureRecognizer working on UIImageView but not on UILabel

最后都变了- 提交于 2019-12-04 05:10:34

问题


I have a UITableViewCell class named CommentsTableViewCell which among other things includes a UIImageView and a UILabel.

Code I'm using:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CommentsTableViewCell.showUserViewController))
nameLabel.userInteractionEnabled = true
avatarRoundImageView.userInteractionEnabled = true
nameLabel.addGestureRecognizer(tapGesture)
avatarRoundImageView.addGestureRecognizer(tapGesture)

As you can understand I have a function which shows another UIViewController whenever the UIImageView or the UILabel is tapped.

What buffles me is that the tapGesture works correctly on the UIImageView but not on the UILabel.

Any ideas?


回答1:


You need different gesture for all control

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CommentsTableViewCell.showUserViewController))
avatarRoundImageView.userInteractionEnabled = true
avatarRoundImageView.addGestureRecognizer(tapGesture)

let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(CommentsTableViewCell.showUserViewController))
nameLabel.userInteractionEnabled = true
nameLabel.addGestureRecognizer(tapGesture2)



回答2:


You need to create two UITapGestureRecognizer object because UITapGestureRecognizer works with single UI element object. So create second TapGestureRecognizer and assign one to UILabel and one to UIImageView.

From UIGestureRecognizer documentation.

A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews. It thus must be associated with that view. To make that association you must call the UIView method addGestureRecognizer(_:). A gesture recognizer doesn’t participate in the view’s responder chain.



来源:https://stackoverflow.com/questions/40483099/uitapgesturerecognizer-working-on-uiimageview-but-not-on-uilabel

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