Search code examples
iosswiftuilabeluitapgesturerecognizergesture-recognition

Why doesn't my UITapGestureRecognizer call its func?


I want things to happen when I tap or double-tap my programmatically declared UILabel, but nothing happens when I press it.

Here's my code, which should print "HR_tap" when I tap the heart_rate_value_UILabel.
But nothing happens.

class CentralViewController: UIViewController 
{
. . .


let heart_rate_value_UILabel: UILabel = 
{
    let this_UILabel = UILabel()
    return this_UILabel
}()
 . . .

override func viewDidLoad() 
{

value_row_x += 120       // + width of heart rate title
heart_rate_value_UILabel.frame = CGRect(x: value_row_x, y: value_row_y, width: value_row_width, height: value_row_height )
heart_rate_value_UILabel.center = CGPoint( x: value_row_x + value_row_width / 2, y: value_row_y + value_row_height/2 )
heart_rate_value_UILabel.textAlignment = .left
heart_rate_value_UILabel.text = "nnn"
heart_rate_value_UILabel.sizeToFit()
// Enable tap gesture detection:
    heart_rate_value_UILabel.isUserInteractionEnabled = true
    heart_rate_value_UILabel.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector( self.HR_tap )))
self.view.addSubview( heart_rate_value_UILabel)
. . .
}

. . . 

@objc func HR_tap()
{
    print("*********************  HR_tap()")
}

Solution

  • It works as coded above. Problem was "cock pit error": I was tapping the wrong UILabel. I had one label for the value being displayed, and one for the title of the value. I mistakenly added tap gesture recog to the value instead of the title.