Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending a parameter argument to function through UITapGestureRecognizer selector

I am making an app with a variable amount of views all with a TapGestureRecognizer. When the view is pressed, i currently am doing this

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

but in my function "handleTap", i want to give it an additional parameter (rather than just the sender) like so

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

How do i send the specific headline (which is unique to every view) as an argument to the handleTap-function?

like image 228
Norse Avatar asked Feb 25 '16 18:02

Norse


People also ask

How do you pass arguments in selector method in Swift?

This is the full source code: import UIKit class ViewController: UIViewController { override func viewDidLoad() { super. viewDidLoad() let tapGesture = CustomTapGestureRecognizer(target: self, action: #selector(tapSelector(sender:))) tapGesture. ourCustomValue = "This is a value we can set" self.

What is UITapGestureRecognizer Swift?

UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer . For gesture recognition, the specified number of fingers must tap the view a specified number of times. Although taps are discrete gestures, they're discrete for each state of the gesture recognizer.


1 Answers

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

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var headline: String?
}

Then use that 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 tried this. It worked great.

like image 84
Dave Batton Avatar answered Sep 19 '22 14:09

Dave Batton