Sending a parameter argument to work through the UITapGestureRecognizer selector

I am making an application with a variable number of views using TapGestureRecognizer. When a view is clicked, I'm doing it now

func addView(headline: String) { // ... let theHeadline = headline let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:")) // .... } 

but in my "handleTap" function, I want to give it an additional parameter (and not just the sender) so

 func handleTap(sender: UITapGestureRecognizer? = nil, headline: String) { } 

How to send a specific header (which is unique for each view) as an argument to the handleTap function?

+6
swift selector uitapgesturerecognizer
source share
1 answer

Instead of creating a generic UITapGestureRecognizer, subclass it and add a property for the header:

 class MyTapGestureRecognizer: UITapGestureRecognizer { var headline: String? } 

Then use this instead:

 override func viewDidLoad() { super.viewDidLoad() let gestureRecognizer = MyTapGestureRecognizer(target: self, action: "tapped:") gestureRecognizer.headline = "Kilroy was here." view1.addGestureRecognizer(gestureRecognizer) } func tapped(gestureRecognizer: MyTapGestureRecognizer) { if let headline = gestureRecognizer.headline { // Do fun stuff. } } 

I have tried this. It worked great.

+25
source share

All Articles