How to 'addTarget' to UILabel in Swift
The handler function for a UITapGestureRecognizer
is passed the UITapGestureRecognizer
as the sender
. You can access the view
that it is attached to with the view
property. I would suggest something like this:
func handleTap(sender: UITapGestureRecognizer) {
guard let a = (sender.view as? UILabel)?.text else { return }
...
}
You will also need to change the signature of your selector:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
or for earlier versions of Swift:
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
SWIFT 5.1
Great answer by @vacawana but I just want to post what a complete code will look like to help a bit. You need to add a isUserInteractionEnabled to the label.. as well as the tapGesture created.
let label = UILabel()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tapGesture)
return label
Don't forget to add @objc before "func handleTap"