-2

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.
    }
    */

}
Chinmay Balutkar
  • 224
  • 3
  • 15

1 Answers1

13

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

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • userInteraction was already enabled in the storyboard , but when i added the code testLabel.isUserInteractionEnabled = true its worked , why is it so? – Chinmay Balutkar Feb 27 '17 at 15:17
  • 1
    I'm not sure. Setting the flag in IB (Interface Builder) should work as well. – Duncan C Feb 27 '17 at 15:33
  • I know i have asked the question again , but i asked because the userInteraction was enabled from the storyboard and it wasn't working – Chinmay Balutkar Feb 27 '17 at 15:38
  • @Ronit, I just tested it, and I was able to add a tap gesture recognizer to a label and get it to respond by checking the "user interaction enabled" flag on the label in IB. (In fact I put the gesture recognizer in the scene in IB. The only custom code I had to write was the action that gets called on the gesture recognizer.) – Duncan C Feb 27 '17 at 16:52