Can we Add Tap Gesture to UILabel?

2020-05-10 05:44发布

问题:

I have added Label in the UIView and created its outlet, then with the help of UITapGestureRecognizer i have added the functionality,but when i tap or click in the label. Label text does not changes. I searched for the similar question and i got the answer also its what I've written but still the label text is not changing. Code written in Swift 3.0. Here's the code i have written -

 import UIKit

class testingViewController: UIViewController {

    @IBOutlet weak var testLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
      let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showDatePicker))
      tap.numberOfTouchesRequired = 1
      tap.numberOfTapsRequired = 1
      testLabel.addGestureRecognizer(tap)
      testLabel.isUserInteractionEnabled = true// after adding this it worked
        // Do any additional setup after loading the view.
    }

  func showDatePicker(){
    print("testing")
  }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

回答1:

Yes you can, but you need to set the label's isUserInteractionEnabled flag to true