How to "add Target" to UILabel in Swift

I am trying to add labels to Swift that are being added to the loop. Then I want to add the โ€œTapGestureโ€ event for each of them as I add. It works, but the problem is that the called function takes the data from the label for use when pressed, but the label was overridden by that time, and it takes data from the last one added, and not the one that was pressed. How can I make everyone 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 following is the gesture recognizer code that receives and uses tag data:

 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) } 
+7
uilabel swift addtarget
source share
1 answer

The handler function for UITapGestureRecognizer is passed to UITapGestureRecognizer as sender . You can access the view to which it is attached 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:") 
+6
source share

All Articles