UITapGestureRecognizer在UIImageView上工作但在UILabel上没有
我有一个名为CommentsTableViewCell
的UITableViewCell
类,其中包括UIImageView
和UILabel
。
我正在使用的代码:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CommentsTableViewCell.showUserViewController)) nameLabel.userInteractionEnabled = true avatarRoundImageView.userInteractionEnabled = true nameLabel.addGestureRecognizer(tapGesture) avatarRoundImageView.addGestureRecognizer(tapGesture)
你可以理解我有一个函数,只要点击UIImageView
或UILabel
它就会显示另一个UIViewController
。
让我感到震惊的是tapGesture
在UIImageView
上正常工作,但在UILabel
上却没有。
有任何想法吗?
所有控件都需要不同的手势
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)
您需要创建两个UITapGestureRecognizer
对象,因为UITapGestureRecognizer
适用于单个UI
元素对象。 因此,创建第二个TapGestureRecognizer
并将一个分配给UILabel
,一个分配给UIImageView
。
来自UIGestureRecognizer
文档。
手势识别器根据对特定视图和所有视图的子视图进行经过测试的触摸进行操作。 因此必须与该观点相关联。 要建立该关联,您必须调用UIView方法
addGestureRecognizer(_:)
。 手势识别器不参与视图的响应者链。