Adding TapGestureRecognizer to UILabel in Swift
Pretty straight forward
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "labelAction:")
mylabel.addGestureRecognizer(tap)
tap.delegate = self // Remember to extend your class with UIGestureRecognizerDelegate
// Receive action
func labelAction(gr:UITapGestureRecognizer)
{
let searchlbl:UILabel = (gr.view as! UILabel) // Type cast it with the class for which you have added gesture
print(searchlbl.text)
}
Based on answer from Taimur Ajmal, Updated for Swift 2.X:
override func viewDidLoad() {
super.viewDidLoad()
...
labelDemo.userInteractionEnabled = true // Remember to do this
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self, action: #selector(didTapLabelDemo))
labelDemo.addGestureRecognizer(tap)
tap.delegate = self // Remember to extend your class with UIGestureRecognizerDelegate
...
}
func didTapLabelDemo(sender: UITapGestureRecognizer)
{
print("you tapped label \(sender)")
}