将 UITapGestureRecognizer 添加到 UIPickerView 的子视图

Add a UITapGestureRecognizer to a subview of UIPickerView

我在 UILabel 上接收 UITapGesture 时遇到问题,UILabelUIPickerView 的子视图。

let statusDisplayLabel = UILabel(frame: CGRect(x: 0,
                                               y: 0,
                                           width: <#width of UIPickerView #>,
                                          height: <# height of UIPickerView row #>))

statusDisplayLabel.isUserInteractionEnabled = true

let tapGesture = UITapGestureRecognizer(target: self,
                                        action: #selector(didTapStatusDisplayLabel(tap:)))

tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
statusDisplayLabel.addGestureRecognizer(tapGesture)



<# UIPickerView #>.addSubview(statusDisplayLabel)



@objc func didTapStatusDisplayLabel(tap: UITapGestureRecognizer){
                print("tapped")
}

UILabel 显示在 UIPickerView 之上。但是 "tapped" 消息永远不会显示在控制台中,因为点击只是穿过 statusDisplayLabel 并移动 UIPickerView 。就好像 UILabel 不存在一样

我错过了什么?

尝试创建 Container View,将您的 UIPickerView 放入该视图并尝试添加标签而不是选择器视图,而是在 Container View 中。

检查以下内容

首先检查视图层次结构,是选择器视图顶部的标签

如果全部正确则

此处遗漏的只有userInteractionEnabled

编辑

您可以使用

调试视图层次结构

EDIT2

您可以在 UIView 的子类中实现 func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? 作为替代解决方案。如果您需要演示,那么我可以 post