Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tap gesture recognizer added to UILabel not working

Tags:

ios

swift

I've the following code to add a gesture recognizer to a UILabel. User Interaction Enabled is ticked on for the label in the storyboard, but when I tap on the label the onUserClickingSendToken method is not being called.

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBOutlet weak var tokenDisplay: UILabel!
    var tapGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action:  #selector(onUserClickingSendToken(_:)))

    override func viewDidLoad() {
        super.viewDidLoad()
        tapGestureRecognizer.numberOfTapsRequired = 1
        tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
    }

    func onUserClickingSendToken(_ sender: Any)
    {
      ....
like image 444
Gruntcakes Avatar asked Jan 20 '17 21:01

Gruntcakes


1 Answers

Initializing the tapRecognizer in viewDidLoad should do it, cause you were targeting self before the view was initialized

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

@IBOutlet weak var tokenDisplay: UILabel!
var tapGestureRecognizer:UITapGestureRecognizer!

override func viewDidLoad() {
    super.viewDidLoad()
    tapGestureRecognizer = UITapGestureRecognizer(target:self, action:      #selector(onUserClickingSendToken(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tokenDisplay.isUserInteractionEnabled = true
    tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
}

@objc func onUserClickingSendToken(_ sender: Any)
{
  ....
like image 123
Faruk Duric Avatar answered Oct 19 '22 07:10

Faruk Duric