Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'addTarget' to UILabel in Swift

I am trying to add labels in Swift, which are added in a loop. I then want to add a 'TapGesture' event to each one as they are added. It works , but the problem is that the function called takes data from the label to use when it's clicked, but the label has been redefined by then and it takes data from the last one added, not the one that was clicked. How can I make each one unique?

self.label.attributedText = self.myMutableString
let tapGesture = UITapGestureRecognizer(target: self, action: handleTap(label))
self.label.userInteractionEnabled=true
self.label.addGestureRecognizer(tapGesture)
self.label.font = UIFont.boldSystemFontOfSize(28)
self.label.sizeToFit()
self.label.center = CGPoint(x: screenWidth, y: top)
if(kilom>=30||self.located==false){
    self.scroller.addSubview(self.label)
    if(device=="iPhone"||device=="iPhone Simulator"){
        top = top+80
    }
    else{
        top = top+140
    }
}

The code below is the gesture recognizer that gets the label data and uses it:

func handleTap(sender:UILabel){
    var a = self.label.text
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

    let resultViewController = storyBoard.instantiateViewControllerWithIdentifier("displayer") 

    self.presentViewController(resultViewController, animated: true, completion: nil)
}
like image 889
gareth power Avatar asked Jun 04 '16 13:06

gareth power


2 Answers

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"

like image 189
Perry Kankam Avatar answered Sep 20 '22 05:09

Perry Kankam


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:")
like image 41
vacawama Avatar answered Sep 20 '22 05:09

vacawama