Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift uitapgesturerecognizer pass parameters

I have a lot of Buttons created programmatically and that can change anytime. my tap gesture :

let apriVideoGesture = UITapGestureRecognizer(target: self, action: #selector(PrincipaleController.apriVideo(_:)))
cont.addGestureRecognizer(apriVideoGesture)

func apriVideo(sender : UITapGestureRecognizer){

}

how can i pass parameters? somethig like this :

let apriVideoGesture = UITapGestureRecognizer(target: self, action: #selector(PrincipaleController.apriVideo(stringa : "ciao")))
cont.addGestureRecognizer(apriVideoGesture)

func apriVideo(sender : UITapGestureRecognizer, stringa : String){

}

sorry for bad english, i'm italian

like image 233
Alessandro Zago Avatar asked Jul 04 '16 11:07

Alessandro Zago


People also ask

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.

How to set tap gesture in ios?

You don't need to switch between the code editor and Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.


1 Answers

First of all, if you are using button then why are you adding tap gesture? You can add target to it as

btn.addTarget(self, action: #selector(self.btnPressed(_:)), forControlEvents: .TouchDragInside)

But still you can achieve you goal using tap gesture as

Using UIView as u have insisted

    class ViewController: UIViewController {

    let arrayOfSongsURL: [String] = []
    let startingTag = 100

    override func viewDidLoad() {
        super.viewDidLoad()
        let height : CGFloat = 100
        let width : CGFloat = 100
        (arrayOfSongsURL as NSArray).enumerateObjectsUsingBlock { (url, index, finished) -> Void in
            
            let v = UIView(frame: CGRectMake(0, CGFloat(index) * height, width, height))
            v.tag = self.startingTag + index
            
            v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleTapGesture(_:))))
            self.view.addSubview(v)
        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    @objc func handleTapGesture(gesture : UITapGestureRecognizer)
    {
        let v = gesture.view!
        let tag = v.tag
        let songURL = arrayOfSongsURL[tag - startingTag]
        
        //Do what you want to do with songURL
    }
}
like image 181
Amit Singh Avatar answered Sep 28 '22 21:09

Amit Singh