RyanTCB
RyanTCB

Reputation: 8224

Add a UITapGestureRecognizer to a subview of UIPickerView

Im having problems receiving a UITapGesture on a UILabel which is a subview of a UIPickerView.

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")
}

The UILabel displays as it should over the UIPickerView. However "tapped" message is never displayed in console as the tap just falls through the statusDisplayLabel and moves the UIPickerView instead. It's as if the UILabel is not there

What am I missing?

Upvotes: 1

Views: 274

Answers (2)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16456

Check following

First check view hierarchy, is label on top of picker view

if all correct then

Here, missing part is only userInteractionEnabled

EDIT

You can debug view hierarchy using

enter image description here

EDIT2

You can implement func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? in subclass of UIView as alternative solution. If you need demo then I can post

Upvotes: 1

Vlad Khambir
Vlad Khambir

Reputation: 4383

Try to create Container View, put into this view your UIPickerView and try to add label not into the picker view, but inside the Container View.

Upvotes: 1

Related Questions